Having trouble separating urls.py - django

Hello I'm a newbie in Django.
I'm creating a blog app for practice and I wanted to separate the urls that relates to the blog application from the urls that relates to the other applications.
Since there are many blog-related url patterns, I just included in the main urls.py.
Here is my urls.py:
My_Project/My_Project/urls.py
urlpatterns = patterns('',
# Blog
url(r'^$', include('app_blog.urls'), name='app_blog'),
# Admin
url(r'^admin/$', include(admin.site.urls), name='admin_page'),
......
My_Project/app_blog/urls.py
urlpatterns = patterns('',
# Index page
url(r'^index/$', index_page),
# User page
url(r'^user/(?P<pk>\d+)/', UserDetail.as_view(), name='user_detail'),
......
So I expected that when I navigate to "www.example.com/index" the browser would show the index_page view and for "www.example.com/user/1", it will show the user detail view for user with id equal to 1.
For some reason, however, it shows the 404 page not found error for both pages.
Where have I gone wrong?

name parameter is for a single url pattern. Remove it from this line in My_Project/My_Project/urls.py
The regex pattern should not be '^$'. Instead just plain ''.
url(r'', include('app_blog.urls'))

The problem is here:
# Blog
url(r'^$', include('app_blog.urls'), name='app_blog'),
~~~
You are restricting your url to an empty path, that means everything that is not an empty path will not be matched against app_blog.urls.
Do this instead:
# Blog
url(r'^', include('app_blog.urls')),

Related

Django Page not found

I want to create urls to go to links like this: examples.com/baiviet/post-example/
*post-example is a slug
this is my root 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'^$', include('blog.urls')),
)
Then, this is my blog/urls.py:
from django.conf.urls import patterns, include, url
from django.contrib import admin
from blog import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^baiviet/(?P<slug>)/$', views.view_post, name='viewpost'),
)
My views.py:
def view_post(request, slug):
getpost = get_object_or_404(Blog, slug=slug)
return render(request, 'view_post.html', {'post':getpost})
And my view_post.html:
{{ post.content }}
The only thing I have is "Page Not Found" Error. I have tried to solve it and it takes me 2 hours before posting this question. I hope that someone can help me solve this problem. Thanks you
The reason for 404 is that in your root urlconf, you have
url(r'^$', include('blog.urls'))
Here, $ indicates end of url pattern. Change that to
url(r'^/', include('blog.urls'))
# ^ note the $ shoudl be replaced by / when you are doing an include.
Here is the relevant documentation:
Note that the regular expressions in this example don’t have a $ (end-of-string match character) but do include a trailing slash. Whenever Django encounters include() (django.conf.urls.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.
The issue with the missing pattern, as alecxe mentions on <slug> would arise after it resolves this issue (404).
EDIT:
For you to access the homepage, you need to have a trailing / or have the setting APPEND_SLASH setting to True. Since your URL Pattern is expecting a prefix of / - Now, if you dont want it, in your root urlconf, change r'^/' to just r'^'
You have an empty capturing group configured for the url:
url(r'^baiviet/(?P<slug>)/$', views.view_post, name='viewpost')
HERE ^
You need to provide a pattern for a slug to match, e.g. alphanumeric, underscore and a dash:
url(r'^baiviet/(?P<slug>[a-zA-Z0-9_-]+)/$', views.view_post, name='viewpost')

django url regular expressions capture invalid url

I want to understand how to create urls / regular expressions to capture and redirect to views those patterns that do not match any defined pattern.
I have a pattern in the url for the project where I am looking for waitlist.
I that does not match I want a to direct it to a project view, which I was assuming would be
caught by the second url below
url(r'^waitlist/', include('waitlist.urls')),
url(r'^.*$', views.my_default_2),
If the user does include the url for waitlist, then it should pass to the app url for a match
and if no match pass through to the wild card, the second line.
url(r'^$', views.index, name='index')
url(r'^.*$', views.my_default),
Is this the correct way to capture invalid/ incorrect url input through the project and the app?
For project you can override 404 view
https://docs.djangoproject.com/en/dev/topics/http/views/#customizing-error-views
for default django raise exception when none found. but you can customize this for your need
You can use default page not found view
Follow this
project/waitlist/urls.py
from django.conf.urls import patterns, url
from waitlist import views
urlpatterns = patterns('waitlist.views',
url(r'^$', 'index', name='index'),
)
handler404 = 'mysite.views.my_custom_page_not_found_view'
project/waitlist/views.py
defaults.page_not_found(request, template_name='404.html')
For reference how defaults.page_not_found works see this link

Django URL changes but doesn't render the proper view

I have a url setup with the following view (the url is in the app and the app urls are included in the project):
url(r'^details/(?P<outage_id>\d+)/$', 'outage.views.outage_details'),
def outage_details(request, outage_id=1):
outage_info = Outages.objects.filter(id=outage_id)
return render_to_response('templates/outage/details.html', {'outage_info': outage_info}, context_instance=RequestContext(request))
When I click on the link from http://localhost:8000 the url in the browser changes to http://localhost:8000/outage/details/1 as it should, but the view doesn't render the right template. The page stays the same. I don't get any errors, the url changes in the browser but the details.html template doesn't render. There is an outage in the DB with an ID of 1.
Any thoughts?
The regular expression r'^details/(?P<outage_id>\d+)/$' does not match the URL http://localhost:8000/outage/details/1. However, it should match the expression r'^outage/details/(?P<outage_id>\d+)/$'.
Perhaps, you can post your entire urls.py to find out which view is actually being called, since you don't get any errors. I suspect your home page is being called for all URLs.
Here is my url setup:
project/urls.py
urlpatterns = patterns('',
url(r'^$', 'outage.views.show_outages'),
url(r'^inventory/', include('inventory.urls')),
url(r'^outage/', include('outage.urls')),
url(r'^login', 'django.contrib.auth.views.login', {'template_name': 'templates/auth/login.html'}),
url(r'^logout', 'django.contrib.auth.views.logout', {'next_page': '/'}),
url(r'^admin/', include(admin.site.urls)),
)
outage/urls.py
urlpatterns = patterns('',
url(r'^', 'outage.views.show_outages'),
url(r'^notes/(?P<outage_id>\d+)/$', 'outage.views.outage_notes', name='notes'),
)
I have since changed the details to notes, since I had another page in a different app with a details url and I didn't want it somehow confusing things.

Page not found at /archive/

EDIT: Figured it out, please see bottom.
I'm writing a simple blog app in Django and deploying it locally using this guide. I've completed the guide and everything was nominal so I decided to extend the functionality to view an archive of blog posts. This is how the index functions at the moment, but I wanted to move it to /archive/. I went to the tutorial again to get refresh my memory and it said I had to do three things:
Write the root URLconf in urls.py
Write the view function in views.py
Write the templates for the views
I edited the URLconf to look like this:
urlpatterns = patterns('',
#other patterns
url(r'^archive/', 'RehabLog.views.archive'),
)
I edited my views.py to add this function:
def archive(request):
posts = Post.objects.filter(published=True)
return render(request, 'RehabLog/archive.html', {'posts':posts})
I've saved it all and restarted foreman. When I load the page I get a 404 error which tells me No Post matches the given query. What am I missing out on?
Answer
I remembered reading the the order of your URLConfs was very important.
Previously I had:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', 'RehabLog.views.index'),
url(r'^(?P<slug>[\w\-]+)/$', 'RehabLog.views.post'),
url(r'^archive/', 'RehabLog.views.archive'),
)
Whereas now I have:
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^archive/', 'RehabLog.views.archive'),
url(r'^$', 'RehabLog.views.index'),
url(r'^(?P<slug>[\w\-]+)/$', 'RehabLog.views.post'),
)
Which now works. Could anyone explain why?
/archive/ URL was first-matched by url(r'^(?P<slug>[\w\-]+)/$', 'RehabLog.views.post') so your actual rule url(r'^archive/', 'RehabLog.views.archive') was never reached. When you changed the order the first rule matched was the right one.

urls.py structure for Django music app

I'm having some issues with the structuring of my Django app's urls.py file.
My project is a basic music player app. You begin by clicking a link for Music, followed by (for example) Artists, then you choose an artist, such as Weezer. The app then displays a list of albums and songs by that artist, rendered on the artist_name.html template by the views.artist_name function.
So far in the navigation of the app, the URL will look like http://localhost/music/artists/Weezer/.
My problem lies with the encoding of the next URL. If I choose the album The Blue Album by Weezer, I return the URL: http://localhost/music/artists/Weezer/The%20Blue%20Album.
This should render a template called artist_album_title.html using the views.artist_album_title function. Instead, it renders the new page using the same views.artist_name function as on the current page.
What seems to be happening is that the regex pattern for the ...Weezer/The%20Blue%20Album/ isn't matching with its related URL pattern in my urls.py file. Being new to Django (and with minimal experience with regex), I'm having a hard time determining what my urls.py file should look like for this kind of app.
Below is my urls.py file as it currently stands. Any help at all with my problem would be welcomed. Thanks guys.
from django.conf.urls import patterns, include
from music.views import home, music, artists, artist_name, artist_album_title
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^$', home),
(r'^music/$', music),
(r'^music/artists/$', artists),
(r'^music/artists/([\w\W]+)/$', artist_name),
(r'^music/artists/([\w\W]+)/([\w\W]+)/$', artist_album_title),
)
artist_album_title function from views.py
def artist_album_title(request, album_title):
album_tracks = Track.objects.filter(album__title=album_title)
return render_to_response('artist_album_title.html', locals(), context_instance=RequestContext(request))
The problem with your urlpatterns is that the url /music/artists/Weezer/The%20Blue%20Album satisfies the first pattern so it doesn't go to the next one. This is because Django executes the patterns in the order they are specified.
In order for this to work you must switch the places of the two patterns like so:
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^$', home),
(r'^music/$', music),
(r'^music/artists/$', artists),
(r'^music/artists/([\w\W]+)/([\w\W]+)/$', artist_album_title),
(r'^music/artists/([\w\W]+)/$', artist_name),
)
The best would be to use the following structure for your urls:
urlpatterns = patterns('',
(r'^admin/', include(admin.site.urls)),
(r'^$', home),
(r'^music/$', music),
(r'^music/artists/$', artists),
(r'^music/artists/(?P<artist_name>[\w\W]+)/(?P<album_title>[\w\W]+)/$', artist_album_title),
(r'^music/artists/(?P<artist_name>[\w\W]+)/$', artist_name),
)
and then your views definition will look like this:
def artist_album_title(request, artist_name,album_title):
and
def artist_name(request, artist_name):
you can read more about the named groups in the url in Django docs here
https://docs.djangoproject.com/en/dev/topics/http/urls/#named-groups