Django notes-urlconf views

Source: Internet
Author: User

I. Database File Import Problems

1. From Django. conf. URLs. defaults import *
From website. Contact. Views import contact, thanks
# This method is not easy to import, because as the number of views increases
# Check whether the new view function has been imported.
# Management is very difficult if the project is very large.
# The length of the Import Statement also affects the appearance of the Code.

 

Urlpatterns = patterns ('',
(R' ^ contact/$ ', contact ),
(R' ^ thanks/$ ', thanks ),
)
2. From Django. conf. URLs. defaults import *
# A better way of writing without importing Functions
Urlpatterns = patterns ('website. Contact. view ',
# This method does not require the view function to be imported. Django will automatically import the required view function.
# However, the Group must use the 'contact 'string instead of the function.
(R' ^ contact/$ ', 'Contact '),
(R' ^ thanks/$ ', 'thank '),
)

 

 

# If there are multiple common headers, you can also
Urlpatterns = patterns ('website. Contact. view ',
(R' ^ contact/$ ', 'Contact '),
(R' ^ thanks/$ ', 'thank '),
)

# If XXX: # You can add the app to the Web if conditions are determined.
Urlpatterns + = patterns ('website. Blog. view ',
(R' ^ index/$ ', 'index '),
)
For example:
From Django. conf import settings
From Django. conf. URLs. defaults import *
From mysite import views

Urlpatterns = patterns ('',
(R' ^ $ ', views. Homepage ),
(R' ^ (/d {4})/([A-Z] {3})/$ ', views. archive_month ),
)

If settings. Debug:
Urlpatterns + = patterns ('',
(R' ^ debuginfo/$ ', views. Debug ),
)

 

3. From website. Contact. Views import *
# * Indicates that all public objects (public objects) of the module are imported to the current namespace,
# Anything that does not start with "_" will be imported. All the code in views, including the East of Import
# The West will import, so this method is absolutely useless.
Urlpatterns = patterns ('',
(R' ^ contact/$ ', contact ),
(R' ^ thanks/$ ', thanks ),
)

 

4. From website. Contact import views
# Recommended method, which is more pyhtonic
# It is easy to control.
From website. Contact import views
Urlpatterns = patterns ('',
(R' ^ contact/$ ', views. Contact ),
(R' ^ thanks/$ ', views. Thanks ),
)

 

2. Passing parameters to the Views Function 

1. Two Methods for passing Parameters

1) Using named groups, non-named regular expression groups
It is also called keyword arguments vs. positional arguments. Location and keyword Parameters
2) passing extra options to view functions (see the example in section 2)
Alias: the captured values parameter passed from the regular expression and the extra options parameter passed from the extra dictionary

 

2. Regular Expressions can be used in urlconf.
Urlconf parameter can be named or passed to the Views function using location parameters.
Here, the regular expression is not special, and the parameters to be passed are enclosed in parentheses. Note that,
When defining a parameter name? P. For example, define a day (? P <day>/D)

 

3. Do not place the variable in the URL
As described below, bar_view and foo_view process the same content, but the template is different. In the following example
Different parameters can be displayed without being placed in the URL. That is, changes to the URL '^ Foo/$ 'will not affect the processing.
This method is very convenient to use in some aspects. The best example is the application of generic views system.

# 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 })
3. the variables passed by dictionary parameters have a higher priority than those transmitted by regular expressions.
Example:
Urlpatterns = patterns ('',
(R' ^ mydata /(? P <ID>/d +)/$ ', views. my_view, {'id': 3 }),
)

Although the value of the request URL is 22, http: // 127.0.0.1/mydata/22, the passed ID parameter is 3.

 

3. urlpattern skills 

1. Do not put URL logic processing in views

The URL is variable, so it is best not to include the URL logic in views processing.
Let's just look at the example below:
Urlpatterns = patterns ('',
#...........
('^ AUTH/user/Add/$', views. user_add_stage), #1
('^ ([^/] +)/([^/] +)/Add/$', views. add_stage), #2
#..........
Obviously, the #2 mode includes the #1 URL, But here/auth/user/Add this
The URL must be specially processed. If it is in views, it should be like this. Apparently
If the corresponding URL changes, the views function will soon become unsuitable. So this is not good.
Def add_stage (request, app_label, model_name ):
If app_label = 'auth' and model_name = 'user ':
# Do special-case code
Else:
# Do normal code

(R '^ somepage/$', views. method_splitter, {'get': Views. some_page_get, 'post': Views. some_page_post }),
#...

 

2. encapsulate the view Function
The following code is redundant.
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 ')

 

How can we simplify it? See the following encapsulation function.
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

 

After encapsulation, the code can be greatly simplified, and urlpattern should look like this
From Django. conf. URLs. defaults import *
From mysite. Views import requires_login, my_view1, my_view2, my_view3

Urlpatterns = patterns ('',
(R' ^ view1/$ ', requires_login (my_view1 )),
(R' ^ view2/$ ', requires_login (my_view2 )),
(R' ^ view3/$ ', requires_login (my_view3 )),
)

 

4. Including other urlconfs

1. Gotcha
Use the include regular expression, which cannot contain $ to indicate the end. In addition, the end must contain/
Example: "R ^/HTTP/"-OK "R ^/HTTP/$" NG
 
2. parameter transfer
If the contained URLs accepts a parameter, it will be passed to any include
.

Similarly, extra urlconf options will pass to each URL contained in the lower layer.
Example: The following two are equivalent.

Set one:
# URLs. py
From Django. conf. URLs. defaults import *
Urlpatterns = patterns ('',
(R' ^ blog/', include ('inner'), {'blogid': 3 }),
)
# Inner. py
From Django. conf. URLs. defaults import *
Urlpatterns = patterns ('',
(R' ^ archive/$ ', 'mysite. Views. archive '),
(R' ^ about/$ ', 'mysite. Views. about '),
(R' ^ RSS/$ ', 'mysite. Views. RSS '),
)
######################################## ######################
Set two:
# URLs. py
From Django. conf. URLs. defaults import *
Urlpatterns = patterns ('',
(R' ^ blog/', include ('inner ')),
)
# Inner. py
From 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 }),
)

<End of this section>

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.