Why does this URL work in Django? It is not in urls.py - django

I've never worked with Django before. I'm taking over a Django project that was started by another programmer, who is now long gone. There is some magic happening in the code that I do not understand. For instance, in this file:
urls.py
I see this:
from django.conf.urls import url, include
from django.contrib import admin
from django.core.urlresolvers import reverse_lazy
from django.views.generic.base import RedirectView
from django.conf import settings
from core import views as core_views
from sugarlab.search.views import validate_collections, create_document, delete_interest, rename_interest, add_url, my_interests
from sugarlab.search.views import content, score, terms
from django.contrib.auth.views import logout as django_logout
from django.conf.urls.static import static
admin.autodiscover()
urlpatterns = [
url(r'^admin/logout/$', django_logout,
{'next_page': '/'}),
url(r'^admin/', admin.site.urls),
url(r'^accounts/logout/$', django_logout,
{'next_page': '/'}),
url(r'^accounts/', include('allauth.urls')),
url(r'^unsecured/$', core_views.home),
The confusing part is these two lines:
from django.conf import settings
url(r'^accounts/', include('allauth.urls')),
"allauths" is some configuration set inside of this file:
settings/common.py
The data looks like this:
'allauth',
'allauth.account',
'allauth.socialaccount',
'django.contrib.auth',
'django.contrib.sites',
# Social/3rd party Authentication apps
'allauth.socialaccount.providers.linkedin_oauth2',
'captcha'
Somehow this is a URL that actually works:
/accounts/signup/
This file is completely blank:
settings/__init__.py
So I've two questions:
how does "import settings" manage to magically import allauths?
how does /accounts/signup/ map to an actual view? I don't see anything in urls.py, nor in settings, that would make me think that /accounts/signup/ is a valid url.

how does /accounts/signup/ map to an actual view? I don't see anything in urls.py, nor in settings, that would make me think that /accounts/signup/ is a valid url.
url(r'^accounts/', include('allauth.urls')),
there is another urls file inside the app called allauth if it's installed by "pip" you can find it in the following directory "lib/python*/site-package/allauth"
= the python version you are using for example 2.7 or 3.5
ps allauth is a well known 3rd party app you can quick google search django allauth and you'll find it
how does "import settings" manage to magically import allauths?
it doesnt import settings is used for something else for example setting static file url like that
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

Related

Django not using updated urls.py - returning 404 on www.site.com/page with outdated list

I am very new to django and beginning to understand some of the framework however view-route binding is confusing me
There is a persistent issue that when I try to visit any url except for the homepage and /admin I receive a 404, including routes I have declared in my project's urls.py file
also i am following this mdn tutorial
project urls.py
"""trends URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.views.generic import RedirectView
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('articles/', include('articles.urls')),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
app named 'articles' urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
app named 'articles' views.py
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the articles index.")
and here is the 404 page I receive
I know this is becoming very long but there is one more odd thing, when I refresh the 404 page, it will toggle between showing me the above screenshot and sometimes show me an old route which is no longer in the urls.py like this
this is on an nginx server with gunicorn, and restarting the nginx service does not solve the issue
In your projects urls.py you have defined
path('articles/', include('articles.urls')),
So by going to YOUR_URL/articles will not give a valid response. Instead try going to YOUR_URL/articles/ or change your path to
path('articles', include('articles.urls')),
Stumbled upon this SO post which lead me to the idea to restart gunicorn and that solved my problem so try running
sudo service gunicorn restart
should fix your problems

how to correctly import urls.py from app?

This is probably pretty simple but I can't get my head around it. I'm learning Django, have v3.0.4 installed and can't get the URLs from an app to work correctly.
On the project urls.py I have the following:
Project\urls.py:
from django.contrib import admin
from django.urls import path
from django.urls import include
from AppTwo import views
urlpatterns = [
path('', views.index, name='index'),
path('', include('AppTwo.urls')),
path('admin/', admin.site.urls),
]
I've created an app named "AppTwo" and have the following urls.py and views.py in the app:
AppTwo\urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('/help', views.help, name='help'),
]
AppTwo\views.py:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return HttpResponse("<em>My Second App</em>")
def help(request):
return HttpResponse("<em>Help Page!!!</em>")
If I browse to http://127.0.0.1:8000/ the index page loads and I see the text "My Second App" as expected. However if I browse to http://127.0.0.1:8000/help I get page not found 404 error.
I can also browse to the admin page just fine. So far this is a stock project, the only other change I made after creating it was to the settings.py file to install the "AppTwo" application. Based on the documentation, this looks like it should work, so what am I doing wrong?
yep, knew it was simple.
Changed
path('/help', views.help, name='help'),
to:
path('help/', views.help, name='help'),
all good now.

Django URL mapping - NameError: name X is not defined

[A similar question was asked, but not marked as answered, here. I considered continuing that thread but the website told me I'm only supposed to post an answer, so it seems I have to start a new topic.] I'm trying to follow this tutorial and I'm having problems with the URL mapping. Specifically with the part described as "So best practice is to create an “url.py” per application and to include it in our main projects url.py file". The relevant, I hope, part of the folder structure, which arose by following steps of the tutorial to the letter (if possible; usage of the 'patterns' module was impossible for example) and using Django 1.10 is the following:
myproject/
myapp/
urls.py
views.py
myproject/
urls.py
The myproject/urls.py is as follows:
from django.conf.urls import include, url
from django.contrib import admin
admin.autodiscover()
from myapp.views import hello
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^myapp/', include(myapp.urls)),
]
The myapp/urls.py is as follows:
from django.conf.urls import include, url
urlpatterns = [
url(r'^hello/', myapp.views.hello),
]
The myapp/views.py is as follows:
from django.shortcuts import render
def hello(request):
return render(request, "hello.html", {})
However, running 'python manage.py runserver' results in the following error:
url(r'^myapp/', include(myapp.urls)),
NameError: name 'myapp' is not defined
INSTALLED_APPS in settings.py contains 'myapp'.
I'd be greatful for any tips on how to deal with the NameError! [Or any tips whatsoever that anyone might consider to be helpful!]
You have the NameError because you are referencing myapp in myproject/urls.py but haven't imported it.
The typical approach in Django is to use a string with include, which means that the import is not required.
url(r'^myapp/', include('myapp.urls')),
Since you have move the hello URL pattern into myapp/urls.py, you can remove from myapp.views import hello from myproject/urls.py.
Once you've made that change, you will get another NameError in myapp/urls.py. In this case, a common approach is to use a relative import for the app's views.
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^hello/$', views.hello),
]
Make sure you have imported following modules to urls.py.
from django.conf.urls import url
from django.contrib import admin
in django 2.0
use these
from django.contrib import admin
from django.urls import path
from first_app import views
urlpatterns = [
path('',views.index, name="index"),
path('admin/', admin.site.urls),
]
your app URL has to be a string
so, here is how the code should look like.
from django.conf.urls import include, url
from django.contrib import admin
admin.autodiscover()
from myapp.views import hello
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^myapp/', include('myapp.urls')),
]
also, note that from python 2 upward the regular expression is not needed.
change URL to path
from django.conf.URLs import include path
from Django.contrib import admin
admin.autodiscover()
from myapp.views import hello
urlpatterns = [
path('^admin/', include(admin.site.urls)),
path('^myapp/', include('myapp.urls')),
]
In Django 2.1.7 here is the default urls .py file
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
so we need to add this line as well
from django.conf.urls import url
I have followed #Alasdair answers
You have the NameError because you are referencing myapp in myproject/urls.py but haven't imported it.
The typical approach in Django is to use a string with include, which
means that the import is not required.
Unfortunately, it didn't work out(I still got the name X is not defined error). Here is how I do it.
from django.contrib import admin
from django.urls import include
from django.conf.urls import url
from article import urls as article_users
from article import urls as user_urls
urlpatterns = [
path('admin/', admin.site.urls),
path('api/article/', include(article_users)),
path('api/user/', include(user_urls)),
]
Before using the URL command be sure to first import the url from the module Urls. Then try using the runserver.
from django.conf.urls import url
from django.contrib import admin
from django.urls import path

Page not found 404 on Django site?

I'm following the tutorial on Django's site to create a simple poll app. However, Django is unable to resolve "//127.0.0.1:8000/polls" , even though I've defined the regex in mySite/urls.py. I'm doing this in a virtualenv, with the latest Django (1.7) installed.
mySite/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^polls/', include('polls.urls')),
)
mySite/polls/urls.py:
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
)
mySite/polls/views.py:
from django.shortcuts import render
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the polls index.")
mySite/settings.py:
...
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'polls',
)
....
ROOT_URLCONF = 'mySite.urls'
The error I'm getting:
Using the URLconf defined in mySite.urls, Django tried these URL patterns, in this order: ^admin/
The current URL, polls, didn't match any of these.
I had the same problem.
It turns out I was confused because of the multiple directories named "mysite".
I wrongly created a urls.py file in the root "mysite" directory (which contains "manage.py"), then pasted in the code from the website.
To correct it I deleted this file, went into the mysite/mysite directory (which contains "settings.py"), modified the existing "urls.py" file, and replaced the code with the tutorial code.
In a nutshell, make sure your urls.py file is in the right directory.
Django unable to resolve 127.0.0.1:8000/polls because url config defined as r'^polls/'.
Usual workaround:
mySite/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^polls/', include('polls.urls')),
)
Note:
Whenever Django encounters include(), It chops off whatever part of the URL matched up to that point and sends the remaining string to the included URLconf for further processing.
mySite/polls/urls.py:
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('polls.views',
url(r'^$', 'index', name='index'),
)
Note: Instead of typing that out for each entry in urlpatterns, you can use the first argument to the patterns() function to specify a prefix to apply to each view function.
Answer If
If you want to access 127.0.0.1:8000/polls Note: without trailing slash
use view based url
url(r'^polls', 'polls.views.index', name='index'),
So now you can access 127.0.0.1:8000/polls without trailing slash.
You're accessing to http://yourdomain.com/, and you don't have any URL defined for "/".
You have two options:
If you want to access to the index page of your polls application you have to enter the URL: yourdomain.com/polls
You can also modify you mySite/urls.py file to access from just yourdomain.com
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', include('polls.urls')),
)
To make the answer clear for beginners who has this issue by following the tutorial, the project root URLconf is the one in the same folder as settings.py which is:
mysite/mysite/urls.py
Just make sure import 'include'. The code looks like:
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^polls/', include('polls.urls')),
]
So in
mysite/mysite/settings.py:
The line should be:
ROOT_URLCONF = 'mysite.urls'
You don't need create a fresh new root URLconf.
Depending on where you put your ROOT urls.py, you set your ROOT_URLCONFIG accordingly, if you have it in your outermost folder containing manage.py then "urls" is ok. if you have it in someother folder then you have to do ".urls"
Credit for the answer to jerryh91
For more info about how it works, check How Django processes a request
You put the urls.py folder into the outer MySite folder, you are suppose to put it in the inner one so its not mySite/urls.py, but mySite/mySite/urls.py:
ran into the same mistake when i did the tutorial
Another way to access 127.0.0.1:8000/polls would be to redirect the browser when accessing 127.0.0.1:8000. It is done by editing .../mysite/mysite/urls.py as follows:
from django.conf.urls import include, url
from django.contrib import admin
from polls import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^polls/', include('polls.urls', namespace='polls')),
url(r'^$', views.index, name='index'),
]
Page not found?
If you get an error page here, check that you’re going to http://localhost:8000/polls/ and not http://localhost:8000/.
Source : https://docs.djangoproject.com/en/3.0/intro/tutorial01/
Actually the problem is that you didn't notice that
mysite/urls.py and polls/urls.py are two different files and you modified polls/urls.py instead of putting mysite/urls.py in the urls.py file in ...mysite\mysite folder.
In my case, it was a stupid mistake. I wanted to integrate the plugin django-tinymce, and test it. So following this guide, I did the step 3 and exported the variable to the path. As the server runned again, I received the not found error, showing the message:
Using the URLconf defined in testtinymce.urls, Django tried these URL
patterns, in this order: ....
But I didn't know what exactly it was, until I remembered exporting the variable DJANGO_SETTINGS_MODULE
running unset DJANGO_SETTINGS_MODULE in terminal solved my issue. Hope that it helps someone too.
Add the below line in your Mysite/urls.py
url(r'^$', views.index, name='index'),
and check. If you have created your project correctly, it should work. Else something like above might have happened to have more than one files so confused.
2017-10-05_12:03 ~/mysite/mysite
$ vi urls.py
2017-10-05_12:04 ~/mysite/mysite
$ cd ../..
2017-10-05_12:04 ~
$ mv mysite SENSIBLE_NAME_DJANGO_ROOT
i had the same issue and got it resolved by adding /polls after http://server:port/ and so final address in server looks like:
http://server:port/polls

Display static page in Django

I am trying to display contents of a static page in Django project.
urls.py :-
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'spollow.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
(r'^$', 'django.views.generic.simple.direct_to_template', {'template': 'index.html'}),
url(r'^admin/', include(admin.site.urls)),
)
index.html is in the same directory as urls.py
I am getting 500 internal server error. Any ideas where I am going wrong?
First of all, what is the stacktrace from the 500 error saying that the error may be? You may be using Django 1.6 and the call to direct_to_template is deprecated.
On Django 1.5 or newer you can use TemplateView
Here's the example from the documentation
https://docs.djangoproject.com/en/dev/topics/class-based-views/
from django.conf.urls import patterns
from django.views.generic import TemplateView
urlpatterns = patterns('',
(r'^about/', TemplateView.as_view(template_name="about.html")),
)
You can use the direct_to_template view on Django 1.4 or older
Here's the relevant documentation
https://docs.djangoproject.com/en/1.4/ref/generic-views/#django-views-generic-simple-direct-to-template
from django.views.generic.simple import direct_to_template
urlpatterns = patterns('',
(r'^foo/$', direct_to_template, {'template': 'foo_index.html'}),
(r'^foo/(?P<id>\d+)/$', direct_to_template, {'template': 'foo_detail.html'}),
)
If it is the latter, I would use a module instead of string, (look at the import on the example).
Other than that, without the 500 details it will be shooting in the dark, you may not have the right template, or an incorrect path, or a million different things.
Bonus note
If you just want to serve static pages, it might be better to serve them through the actual webserver in front of django (nginx, apache, etc), specially if you are expecting a high volume of traffic.
If Your error is due to unable to find index.html
if yours is an app(ie: created by python manage.py startapp <app>) then:
Then django will search for template files in <app>/templates directory, if you added the app to INSTALLED_APPS in settings.py.
so you need to create a folder templates inside your <app> and put index.html inside it.
if you don't have any apps, you want to add the template path manually :
open settings.py, then edit TEMPLATE_DIRS
TEMPLATE_DIRS = (
# Put the full path of the template dir here, like "/home/html/django_templates" or
# "C:/www/django/templates".
)
In Django 1.5 or newer you can use the render function instead of direct_to_template:
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^$', 'django.shortcuts.render', {'template_name': 'index.html'}),
)
Or if you prefer the more complex way :), you can use class-based TemplateView:
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name="index.html")),
)