In depth understanding of Urls

Directory index:

One, the essence of Django URL

Two, analysis of the patterns () function

Three, analysis of the URL () function

Four, the include () function

Five, URL advanced configuration


One, the essence

(1): It is the nature of the URL model and the URL model between view function is called mapping table.

Django-admin.py startproject is running, the script will automatically for you to build a URLconf (URL configuration) (urls.py file). Because it is pure Python code (pure Python code), can be created dynamically(Dynamically Constructed).


(2): Django put this record to ROOT_URLCONF

ROOT_URLCONF

Default: Not defined

Automatically create settings.py contains a ROOT_URLCONF configured to automatically generate the urls.py. to open the file settings.py and you will see the following:

ROOT_URLCONF = 'mysite.urls'
The corresponding file is MySite/urls.py

A string representing the complete Python into path URLconf root, such as ’ mydjangoapps.urls’, can cover according to each request by setting the urlconf property to HttpRequest objects.


(3): When accessing the URL /hello/, Django according to the ROOT_URLCONF setting load URLconf. Then sequentially matching in URLconf URLpatterns, until a match is found. When it finds the matching URLpatterns calls the view function, and the HttpRequest object as the first argument.


(4): The view function must return a HttpResponse, Django convert HttpResponse into a suitable HTTP response, displayed in Web page


Two, the patterns () function

urlpatterns should be a Python list, in the format returned by the function patterns()

#django.conf.urls.defaults.patterns()
django.conf.urls.defaults import *  #  import patterns()

patterns(prefix, pattern_description, ...)

The first arguement to patterns() is  A string prefix (prefix)

The remaining (arguements should be tuples remaining) :

In general we will patterns () function returns the value stored in the urlpatterns variable.

Once one of the regexes matches, Django imports and calls the given view, which is a simple Python function.

The view function using the HttpRequest object as the first argument, any value of regular expressions to capture as the other parameters.

def myblog(request,id,name):
    pass

Three, the URL () function

You can use the url() function, instead of a tuple, as an argument to patterns()

Grammar:

url(regex, view, kwargs=None, name=None, prefix='')
urlpatterns =patterns('djtest.views',
     (r'^json/$','json'),
     url(r'^geturl/$','geturls',name='get_urls'),                         
)

#If the patterns (no prefix), can also be: 
urlpatterns += patterns('',
    url(r'^geturl2/$','geturl2',name='geturl2_test',prefix='djtest.views'),
)

Four, the include () function

include(<module or pattern_list>)

your urlpatterns can “include” other URLconf modules!

Usually used for classification, so that the project URLs highly unified.:

urlpatterns +=patterns('',
     (r'^blog/',include('myblog.urls')),        #URLs myblog app
     (r'^manage/',include('manager.urls')),     #URLs manage app
)

Be careful:

(1),include() Regular expression does not include a $(end of string matcher), but includes a diagonal rod/.

(2),When Django met include (), it will be truncated matching URL, and put the rest of the string to the URLconf for further processing.

As in myblog.app URLs.:

#In myblog.app URLs
urlpatterns =patterns('myblog.views',
     (r'^index/$','index'),     #The blog page                   
)

Then we discuss the include (pattern matching).:

(1):Not containing variable parameters

As in the URL input box, it will intercept (include) matching URL, this is ” blog” then find the host is myblog.urls, then the remaining part here is ” index” to match the myblog.urls in URL mode.

(2):Containing variable parameters (such as a named group)

#root urls
urlpatterns += patterns('',
   (r'^(?P<username>\w+)/blog/',include('blog.urls')),                        
)

#blog.urls
urlpatterns = patterns('blog.views',
        (r'^index/$','index'),
        (r'^other/$','other'),
)

#blog.views
def index(request):
    return HttpResponse('ok')

#Parameter variables
def other(request,username):
    return HttpResponse(username)

The captured username variable will transfer to the included URLconf, and then transferred to the URLconf every view function.

Then in a browser:

Then the output: BeginMan

More complex:

(r'^blog/(?P<username>\w+)/(?P<user_id>\d+)/',include('blog.urls'))    

#.....
def index(request,username,user_id):
    return HttpResponse('ok:%s,%s' %(username,user_id))

Input:

Output: ok:BeginMan,20

Pay attention to the back and don't forget to which URLs to match blog urls. Such as(r'^index/$’)


Five, URL advanced configuration

Reference: Django system knowledge (10): URL common configuration method [reprint]

Here a part.

1,A named group:

No named regular expression groups, namely, on the part of URL we want to capture with parentheses, Django will capture the text to the view function as a positional parameter.

Named regular expression groups to capture URL, and sends the data to the view as a keyword parameters.

Named regular expression groups of grammar:

(?P<name>pattern)

Name: group name

A pattern: matched pattern, common:

Symbol Matching. Any single character \d to match any digital [A-Z] matching A-Z any uppercase [a-z] matching A-Z any lowercase letter [A-Za-z] matching A-Z any letter regardless of the size of write + matches one or more (such as: \d+) [^xxx]+ matches one or more non XXX (such as [^name]+)? Matches zero or one (such as: \d?) * matches zero or more (e.g.: \d*) {a,b} The matching between a ,B (e.g.: \d{1,3}One or two or three numbers)


Examples are as follows:

('^position/(\d{4})/(\d{2})/$','position'),             #No named regular expression groups
('^name/(?P<year>\d{4})/(?P<month>\d{2})/$','name'),    #A named group

Address: input, processing in the corresponding view function

#The position parameters of the form, if the position change, such as (request, month, year), then the corresponding value will change
def position(request,year,month):
    return HttpResponse('position:%s--%s' %(year,month))
    #Output: position:2013--10
    
#Keyword parameters, key-value mapping, regardless of location, so when the position change, constant
def name(request,month,year):
    return HttpResponse('name:%s--%s' %(year,month))

2,Additional arguments passed to the view function

Each pattern inside the URLconf can contain third data: a dictionary of keyword arguments.

('^foo/$','commonView',{'name':'foo','age':22}),
('^bar/$','commonView',{'name':'bar','age':12}),


def commonView(request,name,age):
    return HttpResponse('name:%s--age:%s' %(name,age))

The input, output: bar, foo

A common application is to transfer the template:

# urls.py

from django.conf.urls.defaults import *
from mysite import views

urlpatterns = patterns('',
    (r'^foo/$', views.foobar_view, {'template_name': 'template1.html'}),
    (r'^bar/$', views.foobar_view, {'template_name': 'template2.html'}),
)

# views.py

from django.shortcuts import render_to_response
from mysite.models import MyModel

def foobar_view(request, template_name):
    m_list = MyModel.objects.filter(is_new=True)
    return render_to_response(
template_name,
 {'m_list': m_list})

Posted by Angela at November 28, 2013 - 10:45 AM