Python--django's URL Controller

Source: Internet
Author: User

1. The View layer Routing configuration system (views)

The URL configuration (URLconf) is like the directory of the Web site that Django supports. Its essence is the mapping table between the URL and the view function that you want to call for that URL; that's how you tell Django to call that code for that URL and call that code for that URL.

        urlpatterns = [         URL (regular expression, views view function, parameter, alias),] parameter description:    a regular expression string    a callable object, Typically a view function or a string that specifies the path of a view function optional    default argument (dictionary form) to pass to the view function    an optional name parameter    '

Regular string parameters for 2.URLconf

2.1. Simple Configuration

From Django.conf.urls import URL
# #from Blog Import views as blog_views  #可以定义别名
From. Import views urlpatterns = [url (r ' ^articles/2003/$ ', views.special_case_2003), url (r ' ^articles/([0-9]{4})/$ ', views.year_archive), url (r ' ^articles/([0-9]{4})/([0-9]{2})/$ ', views.month_archive), url (r ' ^articles/([0-9]{4})/( [0-9] {2}) /([0-9]+)/$ ', Views.article_detail),]

Features of 2.2.url Matching

    1 Once the match is successful no longer continues    2 to capture a value from a URL, you only need to place a pair of parentheses around it.    3 You do not need to add a leading backslash, because each URL has a. For example, it should be ^articles rather than ^/articles.    4 the ' R ' in front of each regular expression is optional but is recommended to add.

2.3. Unnamed group

URL (r ' article/(\d+)/(\d+) $ ', blog_views.article_yearmonth), # Article_yearmonth (request,2009,12)

Grouping passes the contents of parentheses as arguments to the back of the request. The pass parameter method equals the positional pass.

2.4. The named group (named Group) method is equivalent to the keyword parameter, and is not affected by the position.

Example:

URL (r ' ^blog/article/(? P<year_id>\d+)/(? P<month_id>\d+) $ ', blog_views.article_yearmonth)  # article_yearmonth ( REQUEST,YEAR_ID=2009,MONTH_ID=12)

2.5.url distribution

The URL matching rules for all apps are written to only one URLs, and a lot of records need to be written, so it's not easy to debug and seems confusing. All you need is routing distribution, and the URL matching rules for each app are distributed to the respective apps, and the URL values in the project are defined to the app's distribution rules.

Example:

    # route Distribution    URL (r ' ^blog/', include (' Blog.urls ')),   #将所有跟blog相关的url解析规则放到 Blog app to go.    URL (r ' ^login.htmls/', app01_views.login,name= "login")

2.6. URL Orientation resolution (alias parameters in URLs)

A common requirement when using a Django project is to get the final form of the URL for embedding into the generated content (in the view and the URL displayed to the user, etc.) or for handling server-side navigation (redirection, etc.).

There is a strong desire not to hardcode these URLs (laborious, non-extensible and prone to errors) or to design a specialized URL generation mechanism that is not related to urlconf, because it can easily lead to a certain amount of outdated URLs being generated.

In other words, what is needed is a dry mechanism. In addition to the others, it also allows the design of URLs to be automatically updated without traversing the project's source code to search for and replace outdated URLs.

Get a URL The first thing you think about is the identity of the view that handles it (for example, the name), the other necessary information for finding the correct URL has the type of the view parameter (positional parameter, keyword parameter), and value.

Django provides a way to make URL mappings the only place in the URL design. You fill your urlconf and then you can use it in both directions:

    • Based on a user/browser-initiated URL request, it invokes the correct Django view and extracts its parameters from the URL to the desired value.
    • Gets the URL associated with the Django view based on its identity and the value of the parameter that will be passed to it.

The first way is the usage we've been discussing in the previous chapters. The second way is called reverse parsing the URL, reverse URL match, reverse URL query, or simple URL reverse lookup.

Where URLs are required, Django provides different tools for URL inversion for different levels:

    • In the template: Use the URL template tag.
    • In Python code: Use a django.core.urlresolvers.reverse() function.
    • In higher-level code related to handling Django model instances: Using get_absolute_url() methods.

Example:

The URL in the project is written like this

    URL (r ' ^login.htmls/', app01_views.login,name= "login")

Find the Login method with views from the APP01 application

From django.shortcuts import render,httpresponse# Create your views here.def login (Request):    if request.method== " POST ":        user=request. Post.get ("user")        pwd=request. Post.get ("pwd")        return HttpResponse ("Login Successful! ")    return render (Request," login.html ")

Use the login function to find the page that needs to be requested login.html

The login page reads as follows:

<!DOCTYPE HTML><HTMLLang= "en"><Head>    <MetaCharSet= "UTF-8">    <title>Title</title></Head><Body><formAction= "{% url ' LOGIN '%}"Method= "POST">    <P>Name<inputtype= "text"name= "User"></P>    <P>Password<inputtype= "Password"name= "pwd"></P>    <inputtype= "Submit"></form></Body></HTML>

Python--django's URL Controller

Related Article

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.