Django URL Mapping - Django URL Template | W3school

Now, when you have successfully created a view for your application, you are required to access this view using an associated URL. Django framework owns a separate way of URL mapping which is done with the help of url.py file. You can locate this file under the myproject/url.py path. The file will contain the following code:

Also Read: Django Admin Interface

from django.conf.urls import patterns, include, url

from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns(”,

  #Examples

  #url(r’^$’, ‘myproject.view.home’, name = ‘home’),

  #url(r’^blog/’, include(‘blog.urls’)),

  url(r’^admin’, include(admin.site.urls)),

)

[post_middile_section_ad]

Django controller always steps in whenever a user requests for a web page on your application. In such a scenario, Django controller searches for the associated view. If it is unable to find one, then it displays the 404 Not Found Error. So, to avoid such an error, it is mandatory to perform URL mapping. The most important tuple in the url.py file is urlpatterns. This tuple enables you to perform URL mapping. The following piece of code will help you understand how mapping can be performed with the use of urlpatterns tuple:

from django.conf.urls import patterns, include, url

from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns(”,

  #Examples

  #url(r’^$’, ‘myproject.view.home’, name = ‘home’),

  #url(r’^blog/’, include(‘blog.urls’)),

  url(r’^admin’, include(admin.site.urls)),

  url(r’^hello/’, ‘myapp.views.hello’, name = ‘hello’),

)

This process starts with the mapping of /home URL to the hello view, which is created under the myapp/view.py file. The three major components of a URL mapping are:

  1. Pattern : Regexp helps you to resolve and map the corresponding URL. Everything which falls under the “re” module of Python is eligible to be a pattern.

Note: This is more useful when you are required to pass parameters to a URL.

2. Python Path to View : It works similar to the process of import of a module.

3. Name : This type of URL patterns are used whenever you want to perform URL reversing as shown in above example. Well, once you are done with it, you will be required to run http://127.0.0.1/hello URL to access your matching view.

How to Organize A URL?

As you already know that till now we have been creating URLs under myprojects/url.py file. Well, a known fact about Django is that it is capable of reusing already created applications into different projects. But the problem arises when you start saving all your URLs from different projects under same roof i.e., in the projecturl.py file. To resolve this issue, the best solution could be to create a separate url.py file per application then to integrate this file in various main projects’ url.py file. We have done this before while mapping admin URLs to the corresponding admin interface.

organize URL

How To Do It?

In the given example, we will be creating url.py file for myapp application. The code will appear as the following:

from django.conf.urls import patterns, include, url

urlpatterns = patterns(”, url(r’^hello/’, ‘myapp.views.hello’, name = ‘hello’),)

Now, you are required to perform a few of the changes in the myproject/url.py file.

from django.conf.urls import patterns, include, url

from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns(”,

  #Examples

  #url(r’^$’, ‘myproject.view.home’, name = ‘home’),

  #url(r’^blog/’, include(‘blog.urls’)),

  url(r’^admin’, include(admin.site.urls)),

  url(r’^myapp/’, include(‘myapp.urls’)),

)

[post_middile_section_ad]

In the above provided code, you can see that we have included all the URLs from the myapp application. This simplifies the structure of your web app. So, previously, home.html was accessed through /hello but now, you can access it by using /myapp/hello.

myproject

Now, for an instance, imagine that you have another view “morning” in your myapp application. To map this view in the myapp/url.py file, you are required to make a few changes in the file which are given below:

from django.conf.urls import patterns, include, url

urlpatterns = patterns(”,

  url(r’^hello/’, ‘myapp.views.hello’, name = ‘hello’),

  url(r’^morning/’, ‘myapp.views.morning’, name = ‘morning’),

)

The changes will then appear as the following:

from django.conf.urls import patterns, include, url

urlpatterns = patterns(‘myapp.views’,

  url(r’^hello/’, ‘hello’, name = ‘hello’),

  url(r’^morning/’, ‘morning’, name = ‘morning’),)

Here, we are using the first element of the urlpatterns tuple. This is helpful whenever you want to rename your already existing applications.

URL pattern

How To Send Parameters To Views?

We will start with the basic example of an article where you will be able to access the article by using /articles/article_id. Parameter passing can be achieved by storing the article with the help of regexp in the URL pattern.

Firstly, check for the content of the myapp/view.py file, it should appear as the following:

from django.shortcuts import render

from django.http import HttpResponse

def hello(request):

  return render(request, “hello.html”, {})

def viewArticle(request, articleId):

  text = “Displaying article Number : %s”%articleId

  return HttpResponse(text)

[post_middile_section_ad]

To map the URL in myapp/url.py file, you will be required to access it using /myapp/article/articleId.

from django.conf.urls import patterns, include, url

urlpatterns = patterns(‘myapp.views’,

  url(r’^hello/’, ‘hello’, name = ‘hello’),

  url(r’^morning/’, ‘morning’, name = ‘morning’),

  url(r’^article/(\d+)/’, ‘viewArticle’, name = ‘article’),)

Whenever you enter the URL to the web server (http://127.0.0.1:8000/myapp/article/42), it will pass the parameter as 42 to the viewArticle view. The output on the browser will appear as the following:

passing_parameters_to_viewarticle

 

It is important to make a note of the order of parameters as a parameter passed in reverse order might display a different output. In the following section of code, we will help you to understand the list of articles in a month of a year. Here, we will be adding viewArticles view. The view.py file will carry the following content:

from django.shortcuts import render

from django.http import HttpResponse

def hello(request):

  return render(request, “hello.html”, {})

def viewArticle(request, articleId):

  text = “Displaying article Number : %s”%articleId

  return HttpResponse(text)

def viewArticle(request, month, year):

  text = “Displaying articles of : %s/%s”%(year, month)

  return HttpResponse(text)

The url.py file associated with the above view.py file will appear as the following:

from django.conf.urls import patterns, include, url

urlpatterns = patterns(‘myapp.views’,

  url(r’^hello/’, ‘hello’, name = ‘hello’),

  url(r’^morning/’, ‘morning’, name = ‘morning’),

  url(r’^article/(\d+)/’, ‘viewArticle’, name = ‘article’),

  url(r’^articles/(\d{2})/(\d{4})’, ‘viewArticles’, name = ‘articles’),)

At this final step, you are required to type in the URL as http://127.0.0.1:8000/myapp/articles/12/2006/ on the browser. The output will be “Displaying articles of: 2006/12”. But, in case, you reverse the sequence or order of the passed parameters then you won’t get the same response.

displaying articles

 

To resolve the above mentioned issue, you can link your URL parameter to the View parameter. And to do so, you need to make a few changes in the url.py file, as given below:

from django.conf.urls import patterns, include, url

urlpatterns = patterns(‘myapp.views’,

  url(r’^hello/’, ‘hello’, name = ‘hello’),

  url(r’^morning/’, ‘morning’, name = ‘morning’),

  url(r’^article/(\d+)/’, ‘viewArticle’, name = ‘article’),

  url(r’^articles/(?P\d{2})/(?P\d{4})’, ‘viewArticles’, name = ‘articles’),)