over 7 years ago

When writing a Django project, it happens often that mulitple apps will be included. Let me use an example:

Project
    - Account
    - Journal

In this example, I created a Django project that contains two apps. The Account app handles user registration and login. The Journal app allows users to write journals and save it to the database. Here is the what the urls look like:

#ROOT_URLCONF


urlpatterns = [
    url(r'^account/', include('Account.urls', namespace='account')),
    url(r'^journal/', include('Journal.urls', namespace='journal')), #This namespace name is used later, so just remember we have given everything under journal/ a name

]

This above file is what the ROOT_URLCONF points to. Inside the Note app, the urls look like this:

urlpatterns = [
    url(r'^(?P<id>[0-9]{4})/$', FormView.as_view(), name = 'detail'),
]

So each journal has a 4 digit id. When a journal is access, it's url may look like this: www.mynote.com/note/1231/

Let's say user John bookmarked a journal written by another person. He wants to comment on it. When John tries to access that journal www.mynote.com/note/1231/, he is redirected to the login page. In the login page's view handler, a redirect should be made to Journal ID 1231 once authentication is passed:

def view_handler(request):
    # authentication passed

    return redirect(reverse('detail', kwargs={'id', '1231'}))

The reverse(...) statement is not going to work in this case. Because the view_handler belongs to the Account app. It does not know about the urls inside the Journal app. To be able to redirect to the detail page of the Journal app:

reverse('journal:detail', kwargs={'id', '1231'})

So the format for reversing urls that belong to other apps is:

reverse('namespace:name', args, kwargs)
← Django create and login user manually Understanding Django's Formset 1 →
 
comments powered by Disqus