The use of the Django URL tag and the reverse () function

Source: Internet
Author: User

Using the URL tag and the reverse () function, you can avoid hard-coding URLs in templates and view, so that even if the URL changes, there is no effect on the template and view.

In fact, in the template, view, if you want to get the URL of the current access, then use Request.path or request. Get_full_path () is a more convenient option, of course, if you want to use it in the template

Request object, add ' django.core.context_processors.request ' to this settings configuration item in Template_context_processors

Original: http://www.yihaomen.com/article/python/355.htm

When I first developed the application with Django, it was a hard-coded configuration address in the urls.py, and Httpresponseredirect () was a hard-coded turn-around address in the views.py, and of course it was the same in the template, which brought a problem, If you modify the address of a page in urls.py, all the places (views.py and template) are modified. If it's a big project, there are a lot of places to change. Of course, you might choose a tool that directly looks for replacements to implement. Besides that .....


In fact, Django itself provides this functionality, URL tags, using Django URL tags to implement such a function, in this module: django/conf/urls/defaults

After using the URL tag, no matter how the address in the urlpatterns is changed, the address in the templates does not have to be modified. When calling the URL tag in the template, you need to: {% load URL from the future%}

For example, when a URL function is not used:
Urlpatterns defines the home address of the information,

Program code
Urlpatterns = Patterns (",        (R ' ^article$ ', ' Get_news_index '),)

The HTML in the templates is

And more than one page, there may be a lot of pages to use the information link, then you will have a lot of templates on the page a tag, when one day, you suddenly want to change the address of the term,

Program code
Urlpatterns = Patterns (",        (R ' ^news$ ', ' Get_news_index '),)

You will find that you have to modify the templates 10 <a href= "/article" > Information </a> <a href= "/news" > Information </a>

The hateful thing is that the labels are distributed on different pages, and even worse, you don't know how many such a tags there are (not a single number).

With the URL, the situation is greatly different.
Urlpatterns defines the first page address of the information, if you want to use the URL tag in the template, then add the name parameter to the corresponding URL in Urlpatterns, as follows

Program code
Urlpatterns = Patterns (",        url (r ' ^article$ ', ' Get_news_index ', name=" News_index "),)

The HTML in the templates is

Program code
<a href= "{%url ' appname:news_index '%}" > news </a>

Where AppName is the name of the app that contains the URL, and New_index is the name parameter in the URL (r ' ^article$ ', ' get_news_index ', name= ' News_index ')

How do you change the address of the Urlpatterns, template will change with a lot of trouble.

The address link can be used. Note that the name is global, you can only have a unique name in the whole urlpatterns, this principle should be well understood, as the site's address is also unique.

It is very simple to use URL tags in templates, so what can I do with URLs in views? Previously, when no URL function was used, it might point to an address using the

Httpresponseredirect ("/article")

Of course urlpatterns change the address of the time, all the views of the parameters of the point function must be changed. With the URL function, it becomes:

Httpresponseredirect (Reverse ("News_index"))

The benefits are the same as those used in the template.

When encountering a urlpatterns address that contains parameters, such as:

Program code
(R ' ^ (? P<YEAR>\D{4})/(? p<month>\d{1,2})/$ ', ' get_news_list '),

There are two parameters, the final address such as the archived address http://www.yihaomen.com/2010/02

The situation becomes more complicated, and the usage of urlpatterns is the same:

Program code
URL (r ' ^ (? P<YEAR>\D{4})/(? p<month>\d{1,2})/$ ', ' get_news_list ', name= "news_archive"),

The use of templates needs to be changed, we regard the URL as a method, combined with the templates syntax, the results come out:

Program code
<a href= "{%url ' appname:news_archive ' 2010  

or this:

<a href= "{%url ' appname:news_archive ' year=2010  month=02%}" >2010 year February </a>

Of course, you must also have these two parameters in the views.py method in your background, such as

Program code
def news_list (request,year,month):    print ' year: ', year    print ' Monty: ', Month    ...

The following 2010, 02 is the parameter, the parameters are separated by commas, how many parameters are used the same. Of course, the 2010 02 parameter is obtained by an entity, and the specific case is analyzed.

In the views, with the parameters how to write, million change not to leave the Pope:

Program code
From django.core.urlresolvers import reverse......reverse ("Appname:news_archive", kwargs={"year": $, "month": 02})

For example: Return Httpresponseredirect (Reverse ("appname:news_archive", kwargs={"year":, "month": 02}))

Then, the last resolved address is "/2010/02".

As a result, when developing applications with Django, the URL tag and reverse () function is a very big thing, should be used more, but also for later maintenance to bring convenience.

Django URL tag and use of the reverse () function (GO)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.