Django Book Learning notes-Advanced view and URL configuration

Source: Internet
Author: User

1.URLconf Tips

1). Streamline function Import

Each entry in the URLconf includes the view function it is associated with, passing directly to a function object. This means that the view function needs to be imported at the beginning of the module. But as the Django application becomes more complex, its URLconf is growing, and maintaining these imports can make management cumbersome.

To avoid this hassle, Django provides a way to specify a view function for a particular pattern in URLconf: You can pass in a string that contains the module name and function name, not the function object itself. For example:

From django.conf.urls.defaults Import *urlpatterns = Patterns (", (R ' ^hello/$ ', ' Mysite.views.hello '), (R ' ^time/$ '), ' Mysite.views.current_datetime '), (R ' ^time/plus/(d{1,2})/$ ', ' Mysite.views.hours_ahead '),)

(note the quotation marks before and after the view name.) The quoted ' Mysite.views.current_datetime ' should be used instead of the mysite.views.current_datetime . )

With this technique, you do not have to import the view function; Django will import the appropriate view function the first time it is needed, based on the name and path of the view function described by the string.

When using string technology, you can take a more streamlined approach: extracting a common view prefix. In our URLconf example, each view string starts with ' mysite.views ' , causing too much input.

From django.conf.urls.defaults Import *urlpatterns = Patterns (' Mysite.views ', (R ' ^hello/$ ', ' Hello '), (R ' ^time/$ '), ' Current_datetime '), (R ' ^time/plus/(d{1,2})/$ ', ' Hours_ahead '),)

2). Use multiple view prefixes

If you use string technology, especially if you don't have a common prefix in your URLconf, you may end up blending views. However, you can still use the simple way of view prefixes to reduce duplication. Just add more than one patterns () object, like this:

From django.conf.urls.defaults Import *urlpatterns = Patterns (' Mysite.views ', (R ' ^hello/$ ', ' Hello '), (R ' ^time/$ ', ' Current_datetime '), (R ' ^time/plus/(\d{1,2})/$ ', ' hours_ahead '), urlpatterns + = patterns (' Weblog.views ', (R ' ^tag/(\w +)/$ ', ' tag '),

3). Using named groups

In a Python regular expression, the syntax for a named regular expression group is (?). P<name>pattern) , where name is the name of the group , and pattern is a matching pattern.

From django.conf.urls.defaults import *from mysite Import viewsurlpatterns = Patterns (', R ' ^articles/(? P<YEAR>\D{4})/$ ', views.year_archive), (R ' ^articles/(? P<YEAR>\D{4})/(? P<MONTH>\D{2})/$ ', views.month_archive),)

Using named groups can make your urlconfs clearer, reduce the potential bug that the parameter order might be confusing, and let you reorder the parameters in the function definition. Then the above example, if we want to modify the URL to put the month in front of the year, instead of using named groups, we have to modify the view month_archive parameter order. If we use named groups, the order in which the parameters are extracted in the URL has no effect on the view.

Note: If you use named groups in Urlconf, named and non-named groups cannot exist in the same urlconf mode at the same time.

4). Passing additional parameters into the view

Sometimes you will find that the view functions you write are very similar, only a little bit different. For example, you have two views, their content is consistent, except that they use a different template:

# urls.pyfrom django.conf.urls.defaults Import *from mysite Import viewsurlpatterns = Patterns (', (R ' ^foo/$ ', views.fo Obar_view, {' template_name ': ' template1.html '}), (R ' ^bar/$ ', Views.foobar_view, {' template_name ': ' template2.html '}) ,) # views.pyfrom django.shortcuts import render_to_responsefrom mysite.models import mymodeldef foobar_view (Request, TEMPLATE_NAME): M_list = MyModel.objects.filter (is_new=true) return Render_to_response (template_name, {' m_list ': m_l IST})

5). The priority between the catch value and the extra parameter

When a conflict occurs, the extra urlconf parameter takes precedence over the catch value. That is, if urlconf catches a named group variable with the same name as an extra urlconf parameter, the value of the extra urlconf parameter is used. For example:

From django.conf.urls.defaults import *from mysite Import viewsurlpatterns = Patterns (', R ' ^mydata/(? p<id>\d+)/$ ', Views.my_view, {' id ': 3}),

2. Using Default view Parameters

You can specify a default parameter for a view. This allows the default value to be used when the parameter is not assigned.

# urls.pyfrom django.conf.urls.defaults Import *from mysite Import viewsurlpatterns = Patterns (', (R ' ^blog/$ ', VIEWS.P Age), (R ' ^blog/page (? p<num>\d+)/$ ', Views.page),) # Views.pydef page (Request, num= ' 1 '): # Output the appropriate page of blog entries,    According to Num. # ...

Note: We have noticed that setting the default parameter value is the string ' 1 ', not an integer 1. In order to remain consistent, the value that is captured to Num is always a string.

3. Package View function

Let's say you find yourself repeating a lot of code in various views, like this example:

def my_view1 (Request):    if not  Request.user.is_authenticated ():        return  Httpresponseredirect ('/accounts/login/')     # ...    return  Render_to_response (' template1.html ') def my_view2 (Request):    if not  Request.user.is_authenticated ():        return  Httpresponseredirect ('/accounts/login/')     # ...    return  Render_to_response (' template2.html ') def my_view3 (Request):    if not  Request.user.is_authenticated ():        return  Httpresponseredirect ('/accounts/login/')     # ...    return  Render_to_response (' template3.html ') 

It would be perfect if we were able to remove those repeating generations from each view and only specify them when the authentication was needed. We are able to achieve this by using a view wrapper. Take some time to look at this:

def requires_login (view): Def new_view (Request, *args, **kwargs): If not request.user.is_authenticated (): Return Httpresponseredirect ('/accounts/login/') return view (Request, *args, **kwargs) return New_view

4. Include Other urlconf

At any time, your urlconf can contain other urlconf modules. This is necessary for sites where the root directory is based on a series of URLs. For example, the following urlconf contains additional urlconf:

From django.conf.urls.defaults Import *urlpatterns = Patterns (', (R ' ^weblog/', include (' Mysite.blog.urls ')), (R ' ^ph Otos/', include (' Mysite.photos.urls ')), (R ' ^about/$ ', ' mysite.views.about '),)

Here's a very important place: the regular expression in the example that points to include () does not contain a $ (end-of-string match), but it contains a diagonal bar. Whenever Django encounters an include () , it truncates the matching URLs and sends the remaining strings to the included urlconf for further processing.

5. How the captured parameters and additional parameters work together with the include ()

The parameters that are captured and the extra parameters are always passed to each row in the contained urlconf, regardless of whether the view for those rows requires these parameters. For example, the following two urlconf are functionally equivalent.

# urls.pyfrom django.conf.urls.defaults import * Urlpatterns = patterns (",    " (R ' ^blog/',  include (' inner '),  {' blogID ':  3}), # inner.pyfrom django.conf.urls.defaults import *urlpatterns =  Patterns (",    " (R ' ^archive/$ ',  ' mysite.views.archive '),     (R ' ^ about/$ ',  ' mysite.views.about '),     (R ' ^rss/$ ',  ' Mysite.views.rss '),) 
# urls.pyfrom django.conf.urls.defaults Import *urlpatterns = Patterns (", (R ' ^blog/', include (' inner ')),) # Inner.pyfro    M django.conf.urls.defaults Import *urlpatterns = Patterns ("', (R ' ^archive/$ ', ' mysite.views.archive ', {' blogID ': 3}), (R ' ^about/$ ', ' mysite.views.about ', {' blogID ': 3}), (R ' ^rss/$ ', ' Mysite.views.rss ', {' blogID ': 3}),)


Django Book Learning notes-Advanced view and URL configuration

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.