Reverse lookup Django framework

In use Django project, to obtain the final form of a URL when a common need for embedded into the generated content (URL to the user and other views shown) or for navigation processing server (redirection)

There is a strong wish not to hard-code the URL (laborious, error-prone and not expandable) or design a special URL generation mechanism URLconf irrelevant, because it is easy to lead to a certain extent URL expired.

In other words, when needed a DIY mechanism. Among other points, he also allows the design of URL can be automatically updated without having to traverse the project's source code to search for and replace outdated URL.

Gets a URL information initially thought it was the view of the identification process (such as name), search type (positional parameters, keyword parameters) other necessary information are correct URL parameter view

And value.

Django provides a way is to let the URL mapping URL design is the only place. You fill your URLconf, then use it in both directions:

  The URL request user / browser initiated, its correct adjustment Django view, and extract the value of its necessary parameters from the URL.

  The view identifier Django and its value will be passed to the parameter, the associated URL.

The first way is to use we have discussed in the previous chapter. The second way is called the i direction parse URL, URL matches the reverse, a reverse URL query or simple URL reverse lookup.

URL where needed, for different levels, Django offers different tools for reverse lookup URL:

  In the template: Use the url template tag

  In Python code: using django.core.urlresolvers.reverse () function.

  Examples of the higher-level code associated with the process model Django: using a get_absolute_url () method.

example:

Consider the following URLconf:

from django.conf.urls import url
from . import views

url_patterns = [
    url(r'^articles/([0-9]{4})/$',views.year_archive,name='news-year-archive'),

]

 

Depending on the design here, a year archive URL nnnn corresponds / articles / nnnn /

You can use the following methods in the code template to get them:

<a href="{% url 'news-year-archive' 2012 %}"> 2012 Archive</a>

<ul>
    {% for yearvar in year_list %}
    <li>
          <a href="{% url 'news-year-archive' yearvar %}">{{yearvar}} Archive</a>
    </li>
    {% endfor %}
</ul>

 

In Python code, so used:

from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect

def redirect_to_year(request):

        year = 2006
        return HttpResponseRedirect(reverse(''news-year-arhcive',args=(year,)))

 

Guess you like

Origin www.cnblogs.com/s686zhou/p/11531259.html