English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Django URL Mapping

Now, we have a working view explained in the previous chapter. We hope to access this view through a URL. Django has its own URL mapping method, now let’s edit the url.py file in the project (myproject/urls.py) is completed. The content of the url.py file looks like this:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
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)),
 ) , 'myproject.view.home', name='home'),
    #url(r'^blog/(', include('blog.urls')),
    url(r'^admin', include(admin.site.urls)),
 )

When a user initiates a web request in your web application, Django controller takes over through the url.py file to find the corresponding view, and then returns an HTML response or if not found, returns404Error not found. The most important is the 'urlpatterns' tuple. This is the definition of the mapping between URL and view. A mapped URL pattern is like a tuple -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
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'),
 ) , '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'),
 )

Mark line map URL "/"home" to myapp/ The Hello view created in the view.py file. As you can see from the above mapping, it is composed of three elements -

Pattern - A regular expression that matches the URL to be resolved and mapped. It works with the Python 're' module for all patterns (very useful when you want to pass parameters through URLs). python to the path of the view - the same as when you import the module. Name - To perform URL reversal, it is necessary to use URL pattern naming as shown in the above example. After doing this, start the server and access your view through the following URL: http://127.0.0.1/hello

Organize URLs

So far, we have created “myprojects/url.py”file’s URL, however, as mentioned earlier about Django, it is best to create an application that can be reused in different projects. This way, it is easy to see what the problem is, and if you want to save all the URLs in the “projecturl.py” file. So, the best practice is to create a “url.py” for each application and list it in our main project’s url.py file (including before the URLs managed by our admin interface).

How does it do that?

We need to use the following code to create a urls.py file in the myapp folder (myapp/urls.py) -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import patterns, include, url
 urlpatterns = patterns('', url(r'^hello/', 'myapp.views.hello', name='hello'),)

myproject/urls.py will be changed to the following-

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
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)),
 ) , 'myproject.view.home', name='home'),
    #url(r'^blog/(', include('blog.urls')),
    url(r'^admin', include(admin.site.urls)),
    url(r'^myapp/(', include(myapp.urls)),
 )

We have included all the URLs of the myapp application. This is done by accessing home.html for “/hello”, now it is “/myapp/hello”, this is a better and easier-to-understand structure for web applications.

Create another view file: C:\myproject\templates\myapp\hello.html, with the following content:

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
<html>
 <head>
   <meta http-equiv="content-type" content="text/html; charset=utf-8>
   <title>Hello </title>
   <meta name="robots" content="NONE,NOARCHIVE">
   </style>
 </head>
     <body>
         <h2>Welcome to w3codebox .</h2>
         <p>This is my first Django App</p>
     <body>
 </html>

Now let's imagine another view in the 'morning' of myapp, we hope it will be mapped to myapp/url.py, we will then change our myapp/url.py to -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
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'),
 )

This can be refactored to -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import patterns, include, url
 urlpatterns = patterns('myapp.views',
    url(r'^hello/', 'hello', name = 'hello'),
    url(r'^morning/(', morning', name='morning'),)

As you can see, we now use the first element of the urlpatterns tuple. It is very useful when you want to change the name of the application.

send parameters to the view

Now that we know how to map URLs and how to organize them, let's see how to pass parameters to the view. A classic article example (you want to access the article to “/articles/article_id”)。

Parameters are passed to the view by capturing them through URL pattern regular expressions. If we have a view like the following “myapp/view.py

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
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)

We want to map it to myapp/urls.py, so we can access it through “/myapp/article/articleId” access, we need to add it in the following “myapp/urls.py - Definition

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
from django.conf.urls import url
 from . import views
 urlpatterns = [
     url(r'^hello', views.hello, name='hello'),
     url(r'^article/(\d+)/', views.viewArticle, name='article'), 
     url(r'^', views.index, name='index'),
 ], views.index, name='index'),
 ]


When Django sees the URL:/myapp/article/42”, it will pass the parameter42'Go to the viewArticle view, in the browser, you should get the following result -

Note, the order of parameters here is very important. Suppose we want to view a list of articles for a specific month in a year, now add a viewArticles view. The code in view.py becomes -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
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 viewArticles(request, month, year):
    text = "Displaying articles of: %s"/%s"%(year, month)
    return HttpResponse(text)

The corresponding myapp/urls.py file looks like this −

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
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'),)

Now, when you visit http://localhost:8000/myapp/articles/12/2015/, you will get 'Displaying articles of: 2015/12', but if you convert the parameters, you will not get the same result.

To avoid this situation, it is possible that a URL parameter may link to a view parameter. Therefore url.py will become -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : www.oldtoolbag.com
# Date : 2020-08-08
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'),)