VI. Parametric Transfer of URL s in Django

There is a very powerful URL module in Django, which can make clear URLs according to the developer's idea, and support regular expressions. In addition, parameters can be passed in the URL.

 

1. The way Django handles requests

1) Django is judged by the URLconf module. Usually, this is the value of the ROOT_URLCONF configuration, but if the request carries a property of urlconf (usually set by middleware), then this carried urlconf will replace the configuration of ROOT_URLCONF.

2) Django calls Python Module and find various urlpatterns. This is a belong to django.conf.urls.url() python list of instances.

3) Django traverses each URL pattern, top-down, and picks the pattern that matches the request URL.

4) Once a regular expression of a url pattern is matched, Django imports and calls the relevant view (a simple python function, or a class-based view)

This view will pass the following parameters:

l. An example of HttpRequest

l. If a no named group in the URL is matched, the parameters will correspond one by one according to the location in the URL.

l. If a named group in the URL is matched and parameter passing is matched by named group, the parameter will be replaced by the specified kwargs.

5) If no regular expression is matched, Django throws an exception and reports an error.

 

2. named group in the URL

The URL can pass the specified parameter by named group, with the grammar (??P<name>pattern), name can be understood as the name of the parameter to be passed, and pattern represents the pattern to be matched. For example,

url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', views.month_archive),  

 

So year,month will correspond to the value of year,month passed by views, and the next one will represent the pattern of regular expression matching.

3. Reverse parsing of URLs
Usually, after processing a form, the page will jump. Usually when writing URLs, we avoid hard coding, which is not convenient for later adjustment. Usually we need to get two kinds of content from the URL, the most important thing is that view can get some identification and process through the URL, and other information is the parameters passed through.
Django provides a solution, and the URL mapper corresponds to the URL design one by one. You can do it through URLconf and use it backwards. For example,

 

  • The user initiates the URL request through the browser, calls view, and passes the parameters in the URL to view.
  • By view ing and attaching the corresponding parameters, we can find the corresponding matching URL.

The latter is what we call reverse parsing of URLs. An example of reverse analysis,

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

 

Django also provides tools for reverse parsing of URL s at different levels.

  • In template: use url Tags
  • In python: use the django.core.urlresolvers.reverse() function
  • When processing model instances at a higher level, you can use the get_absolute_url() method

 

4. Use the URL to complete the additional functions of Device and Line table
For information system, we can regard Node, Device and Line as a kind of resource. Any modification of any element of Node, Device and Line, is a modification of resources, but it will be implemented in different tables, but it can be seen in the program as well. Now let's make some changes based on the code in the previous section.


1) Modify the configuration of the URL and extend the URL corresponding to the original add
urls.py:

    from django.conf.urls import url  
    from django.contrib import admin  
    import echo.views  
      
    urlpatterns = [  
        url(r'^admin/', admin.site.urls),  
        #Content display and reverse parsing by defining name  
        url(r'^lists/(?P<table>\w+)/$', echo.views.lists, name='lists'),  
        #add to the content  
        url(r'^add/(?P<table>\w+)/$', echo.views.add, name='add'),  
    ]  

2) Modify the parameters of the view function and add a table after the request so that the function can be used for all tables. Request is a necessary parameter in the views function.
views.py:

    # -*- coding: UTF-8 -*-  
    from .models import Node,Line,Device  
    from forms import NodeForm,LineForm,DeviceForm  
    from django.shortcuts import render, redirect  
    # Create your views here.  
      
    def lists(request, table):  
        #Get the corresponding data from different requests and jump to the corresponding page  
        if table == 'node':  
            data = Node.objects.all()  
            list_template = 'node_list.html'  
        if table == 'line':  
            data = Line.objects.all()  
            list_template = 'line_list.html'  
        if table == 'device':  
            data = Device.objects.all()  
            list_template = 'device_list.html'  
        #Create a context dictionary to pass values to the corresponding page  
        context = {  
            'data': data,  
        }  
        #Jump to the appropriate page and pass the value over  
        return render(request,list_template,context)  
      
    def add(request, table):  
      
        #Get Form data from different Forms depending on the submitted request  
        if table == 'node':  
            form = NodeForm(request.POST or None)  
        if table == 'line':  
            form = LineForm(request.POST or None)  
        if table == 'device':  
            form = DeviceForm(request.POST or None)  
        #Judging whether form is valid  
        if form.is_valid():  
            #To create an instance, we need to do some data processing, not save it for the time being.  
            instance = form.save(commit=False)  
            #Use logged-in users as registrants  
            if table == 'node':  
                instance.node_signer = request.user  
            if table == 'line':  
                instance.line_signer = request.user  
            if table == 'device':  
                instance.device_signer = request.user  
            #Save the instance  
            instance.save()  
            #Jump to the list page, with table parameters, reverse parsing of the URL  
            return redirect('lists', table=table)  
      
        #Create context to centralize data that needs to be delivered to the page  
        context = {  
            'form': form,  
        }  
        #If there is no valid submission, it will remain on the original page.  
        return render(request, 'add.html',  context)  

 

3) Build relevant pages in template:
add.html:

    <pre name="code" class="html"><!DOCTYPE html>  
    <html>  
    <head lang="en">  
        <meta charset="UTF-8">  
        <title></title>  
    </head>  
    <body>  
     <form method='POST' action=''>{% csrf_token %}  
            {{ form }}  
            <input type='submit' value='Submission' />  
     </form>  
      
    </body>  
    </html>  

 

device_list.html:

    <pre name="code" class="html"><!DOCTYPE html>  
    <html>  
    <head lang="en">  
        <meta charset="UTF-8">  
        <title></title>  
    </head>  
    <body>  
        <table>  
            <tr>  
                <th>Name of device</th>  
                <th>Equipment type</th>  
            </tr>  
            {% for item in data %}  
                <tr>  
                    <td>{{ item.device_caption }}</td>  
                    <td>{{ item.device_type }}</td>  
                </tr>  
            {% endfor %}  
        </table>  
    </body>  
    </html>  

 

line_list.html:

    <!DOCTYPE html>  
    <html>  
    <head lang="en">  
        <meta charset="UTF-8">  
        <title></title>  
    </head>  
    <body>  
        <table>  
            <tr>  
                <th>Line Name</th>  
                <th>Line Rate</th>  
                <th>Line type</th>  
            </tr>  
            {% for item in data %}  
                <tr>  
                    <td>{{ item.line_code }}</td>  
                    <td>{{ item.line_speed }}</td>  
                    <td>{{ item.line_type }}</td>  
                </tr>  
            {% endfor %}  
        </table>  
    </body>  
    </html>  

 

node_list.html:

    <!DOCTYPE html>  
    <html>  
    <head lang="en">  
        <meta charset="UTF-8">  
        <title></title>  
    </head>  
    <body>  
        <table>  
            <tr>  
                <th>Node name</th>  
                <th>Node Address</th>  
                <th>Node type</th>  
            </tr>  
            {% for item in data %}  
                <tr>  
                    <td>{{ item.node_name }}</td>  
                    <td>{{ item.node_address }}</td>  
                    <td>{{ item.node_type }}</td>  
                </tr>  
            {% endfor %}  
        </table>  
    </body>  
    </html>  

Keywords: Django Python

Added by kante on Tue, 09 Jul 2019 21:39:12 +0300