Django doesn't load second page - django

I have just started Django, and I'm facing some difficulty.
When the first time I'm loading "localhost:8000/first_app" it is successfully loading index(), but on clicking on "About" link, url is changing to "localhost:8000/first_app/about/", but it is still loading "index()" and not "about()". Don't know what I'm missing.
Here's my project's URL:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^first_app/', include('first_app.urls')),
)
App's URL:
from django.conf.urls import patterns, url
from first_app import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^about/', views.index, name='about'),
)
And views.py:
from django.http import HttpResponse
def index(request):
return HttpResponse("Rango says: Hello world! <br/> <a href='/first_app/about'>About</a>")
def about(request):
return HttpResponse("This is the ABOUT page! <br /> <a href='/first_app/'>Index</a>")
I'm using Django 1.7 and python 2.7.
Thanks.

You need to define your URLs like this;
urlpatterns = patterns('',
url(r'^about/$', views.about, name='about'),
url(r'^/$', views.index, name='index'),
)
Basically '^$' is the beginning & end of the match. The ^ is the start of the pattern & the $ is the end of the pattern so keep that in mind when defining your URLs. It's good practice to use $ to end your urls to avoid views being rendered regardless of what you add to the URL after what you match in your pattern.

Related

Using the URLconf defined in tango_with_django_project.urls, Django tried these URL patterns, in this order:

I've been going through the Tango With Django 1.7 guide and I've come up with the following issue that I'm having troubles fixing:
Using the URLconf defined in tango_with_django_project.urls, Django
tried these URL patterns, in this order:
1. ^$ [name='index']
2. ^about/$ [name='about']
3. ^category/(?P<category_name_slug>[\w\-]+)/$ [name='category']
4. ^admin/
5. ^rango/$
6. ^about/
7. ^category/
8. ^media/(?P<path>.*)
The current URL, rango/category/python, didn't match any of these.
This is my rango/urls.py file
from django.conf.urls import patterns, url
from rango import views
urlpatterns = patterns(' ',
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
url(r'^category/(?P<category_name_slug>[\w\-]+)/$',
views.category, name='category')
)
In tango_with_django_project/urls.py I have
from django.conf.urls import patterns, include, url
from django.contrib import admin
from rango import views
from django.conf import settings
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
url(r'^admin/', include(admin.site.urls)),
url(r'^rango/$', include('rango.urls')),
url(r'^about/', include('rango.urls')),
)
if settings.DEBUG:
urlpatterns+= patterns(
'django.views.static',
(r'^media/(?P<path>.*)',
'serve',
{'document_root': settings.MEDIA_ROOT}),
)
In rango/views.py I have:
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render
from rango.models import Category
from rango.models import Page
def index(request):
category_list = Category.objects.order_by('-likes')[:5]
context_dict = {'categories': category_list}
return render(request, 'rango/index.html', context_dict)
def about(request):
return HttpResponse("Rango says: Hello world! <br/> <a
href='/rango/about'>About</a>")
def category(request, category_name_slug):
context_dict = {}
try:
category = Category.objects.get(slug=category_name_slug)
context_dict['category_name'] = category.name
pages = Page.objects.filter(category=category)
context_dict['pages'] = pages
context_dict['category'] = category
except Category.DoesNotExist:
return render(request, 'rango/category.html', context_dict)
I've been following the guide so I'm not quite sure what the problem is; I had a similar problem earlier on in the guide when I was getting the same error but with /about (never got this fixed).
Any idea what might be causing this problem? Any help is appreciated!
As already commented, the problem here is the definition of the URLconf, more precisely the inclusion of another URLconf that shall define every url that starts with rango/.... The crucial line is this one:
url(r'^rango/$', include('rango.urls')),
which should read instead
url(r'^rango/', include('rango.urls')),
The regex '^rango/$' captures: <start-of-string>rango/<end-of-string>
The regex '^rango/' captures: <start-of-string>rango/<whatever follows>, and that's where your included urls kick in.

Page not found (404) Error in Django

My urls.py is
from django.conf.urls import patterns,url
from rango import views
urlpatterns=patterns('',url(r'^$',views.index,name='index'))
urlpatterns=patterns('',url(r'^about/$',views.about,name='about'))
My views.py is
from django.shortcuts import render
from rango.models import Category
# Create your views here.
from django.http import HttpResponse
def index(request):
category_list = Category.objects.order_by('-likes')[:5]
context_dict={'categories':category_list}
return render(request, 'rango/index.html', context_dict)
def about(request):
return HttpResponse("go to index")
When I am trying to go to the address http://127.0.0.1:8000/rango I am getting page not found. But I am able to go to the address http://127.0.0.1:8000/rango/about.
When I remove the about url pattern in urls.py, I am able to go to the address http://127.0.0.1:8000/rango but not http://127.0.0.1:8000/rango/about, as the about url pattern does not exist.
I am unable to access both urls at once.
You have defined urlpatterns twice. The second patterns containing the about view replaces the first, which stops you accessing the index view.
Instead of,
urlpatterns=patterns('',url(r'^$',views.index,name='index'))
urlpatterns=patterns('',url(r'^about/$',views.about,name='about'))
it should be:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
)
In Django 1.7+, you don't need to use patterns any more, so you can simplify it to
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^about/$', views.about, name='about'),
]

Need a seconda pair of eyes on Django URL dispatcher

Wondering if I could get some help with a second pair of eyes. Started working Django about two months ago learning in my spare time. Long story short: My index and post view work fine. I recently created a contact html\template and view which looks like it goes right back to my index page? Here is my project urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from .settings import MEDIA_ROOT
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/', include('blog.urls')),
url(r'^contact/', include('blog.urls')),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': MEDIA_ROOT}),
)
Here is my app urls.py
from django.conf.urls import patterns, include, url
from blog import views
urlpatterns = patterns('blog.views',
url(r'^(?P<post_name>\w+)/$', views.post, name='post'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^$', views.index, name='index'),
)
If I change my contact view to come up as my default the view it comes up fine.
urlpatterns = patterns('blog.views',
url(r'^(?P<post_name>\w+)/$', views.post, name='post'),
url(r'^$', views.contact, name='contact'),
#url(r'^$', views.index, name='index'),
)
As soon as switch it back to the original state when I click on the contact link on my page it goes right to my index page. I have to be doing something wrong with the URL dispatcher part but I'm not sure what.
Your contact urlpattern is not matching the URL "/contact", it is matching "/blog/contact" and "/contact/contact". Since you've included the blogs urlpatterns under both those prefixes, the thing that matches "/contact" is the URL without anything after the prefix, ie the index.
You probably don't want to put the contact pattern into the included file at all: just match it directly in the base project file.
Please mind the order of the urls in your app's urls.py. Try to put your views.contact view before your views.post view. Keep in mind: Django chooses the first matching regular expression, which is your views.post view.
I ran into a similar problem and described the solution here.
Here your contact view has the url /contact/contact/ and index view has the url /contact/
So you have rewrite the project urls as
from django.conf.urls import patterns, include, url
from django.contrib import admin
from .settings import MEDIA_ROOT
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^blog/', include('blog.urls')),
url(r'^', include('blog.urls')),
url(r'^media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': MEDIA_ROOT}),
)

django tutorial 3 indexpage missing

i am learning django by using django 1.6 documents tutorial 1 - 6.
this round is my 4th try and, previous 3 try was successful and i understand more on every try.
i am in tutorial 3 now, to create views.
according to the documents, after i created a view, i need to map it to a URL.
so i follow the documents to add a urls.py in the polls directory.
and then i follow the document to add include() to mysite/urls.py
i am able to so called wired an index view into the polls view.
now if i go back to localhost:8000, i get an error page,
so my question is
1) WHY?
2) how to get back my localhost:8080 index page co-exist with the polls index page?
thank you very much everyone for your time. i am new and sorry for so simple question.
thank you.
updated:
this is my urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^polls/', include('polls.urls')),
)
this is my polls/urls.py
from django.conf.urls import patterns, url
from polls import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index')
)
the error msg is:
Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order:
^admin/
^polls/
The current URL, , didn't match any of these.
http://localhost:8000 index page will be displayed when you created a project (mysite). After creating an application and including it in installed apps in settings.py, you will no longer view the index page of the project, rather your admin page of the application (polls) will be visible at http://localhost:8000/admin
And if you had created any views with the following patterns in polls/urls.py
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^blog/$', views.blog, name='blog'),
)
You need to visit http://localhost:8000/polls for your index page and http://localhost:8000/polls/blogs for your poll blogs page
Editing my answer for step by step approach:
create index.html at polls/templates/polls directory.
in polls/views.py
from django.shortcuts import render_to_response
def pollindex(request):
return render_to_response('polls/index.html', context_instance=RequestContext(request))
in polls/urls.py
urlpatterns = patterns('',
url(r'^index/$', views.pollsindex, name='index'),
)
in your project/urls.py
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls')),
url(r'^admin/', include(admin.site.urls)),
)
And now you can view your template index.html at http://localhost:8000/polls/index

In Django, How do you write the url pattern for '/' and other root-based urls

I'm new to django, and one of the things that I'm still learning is url_patterns. I set up a pages app to handle the root path (http://www.mysite.com) as well as some static pages such as the about page. I figured out how to set up the url pattern for the root path, but I can't get the site to direct the path '/about' to the pages "about" view.
Here is my main urls.py
from django.conf.urls import patterns, include, url
from django.conf import settings
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls')),
url(r'^$', 'pages.views.root'),
url(r'^/', include('pages.urls')),
)
here is my pages urls.py
from django.conf.urls import patterns, include, url
urlpatterns = patterns('pages.views',
url(r'^about', 'about'),
)
Here is my pages views.py
# Create your views here.
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
def root(request):
return render_to_response('pages/root.html',context_instance=RequestContext(request))
def about(request):
return render_to_response('pages/about.html',context_instance=RequestContext(request))
If I change the main urls.py file to have r'^a/', include('pages.urls') then the path '/a/about' directs to the about action.. so I think it has to be an issue in the way i'm writing the url pattern in this file. But, I can't figure out how to change it. Can anyone help?
Figured out what the issue is. The proper url_pattern on the project level is:
urlpatterns = patterns('',
url(r'^polls/', include('polls.urls')),
url(r'^$', 'pages.views.root'),
url(r'', include('pages.urls')),
)
When this is in place, '/about' and other simple paths direct properly.
Thanks everyone!
Try this, for url.py on the project level:
urlpatterns = patterns('',
# Examples:
url(r'^$', 'apps_name.views.home', name='home'),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
(r'^about/', include('about.urls')),
)
and then the url.py for the app about
urlpatterns = patterns('',
url(r'^$', direct_to_template, {"template": "about/about.html"}, name="about"),
)
Take into account that regular expression are evaluated from top to bottom, then if the path fits the regexp it will enter. To learn more about regexp google it or try the great book from Zed Shaw about regexps
Note that from Django version 2.0 the URL pattern has changed to use django.urls.path() Check Example here: link
from django.urls import path
from . import views
urlpatterns = [
# ex: /polls/
path('', views.index, name='index'),
# ex: /polls/5/
path('<int:question_id>/', views.detail, name='detail'),
# ex: /polls/5/results/
path('<int:question_id>/results/', views.results, name='results'),
# ex: /polls/5/vote/
path('<int:question_id>/vote/', views.vote, name='vote'),
]
About the url method:
url(r'^$', 'pages.views.root')
url is deprecated in Django 3.1, it's good to use re_path instead.
https://docs.djangoproject.com/en/3.1/ref/urls/#s-url
https://docs.djangoproject.com/en/3.1/ref/urls/#re-path
Note: The r'^$'pattern WON'T work with path function, and will give you a misleading error that the route could not be found.
You have to use re_path(r'^$', [etc]) every time you use a regular expression instead of a simple string in pattern.