(7) Django framework learning-Views, advanced usage of URLconf

Source: Internet
Author: User
Document directory
  • Advanced usage of Views and URLconf
The advanced usage of Views and URLconf has previously introduced some basic usage of views and Path Matching. Here we will introduce some advanced usage of Views and URLconf. URLconf: Because urls. py is also a python file, you can use any syntax allowed by python in this file. Let's take a look at the previous example:

FromDjango. conf. urls ImportPatterns, include, url
FromBooks. views ImportHello, search_form, Search, Contact, thanks

Urlpatterns = patterns ('',
Url (R' ^ hello/$ ', hello ),
Url (R' ^ search/$ ',Search),
Url (R' ^ contact/$ ', contact ),
Url (R' ^ contact/thanks/$ ', thanks ),
)

The corresponding modules need to be imported for each Path Matching. Therefore, when the app specification grows, the second line of import Statement

The longer it is... Therefore, you can use the following methods: 1. Only import to the module. You do not need to write a function. FromDjango. conf. urls ImportPatterns, include, url
FromBooks ImportViews
Urlpatterns = patterns ('',
Url (R' ^ hello/$ ', views. hello ),
Url (R' ^ search/$ ', views. Search),
Url (R' ^ contact/$ ', views. contact ),
Url (R' ^ contact/thanks/$ ', views. thanks ),
)

2. Use a string to represent the views function to be executed. You need to write the full path here.

FromDjango. conf. urls ImportPatterns, include, url

Urlpatterns = patterns ('',
Url (R' ^ hello/$ ', 'books. views. hello '),
Url (R' ^ search/$ ', 'books. views. search '),
Url (R' ^ contact/$ ', 'books. views. contact '),
Url (R' ^ contact/thanks/$ ', 'books. views. thanks '),
)

3. For simpler string writing, use the first parameter of patterns ().

FromDjango. conf. urls ImportPatterns, include, url

Urlpatterns = patterns ('books. view ',
Url (R' ^ hello/$ ', 'Hello '),
Url (R' ^ search/$ ', 'search '),
Url (R' ^ contact/$ ', 'Contact '),
Url (R' ^ contact/thanks/$ ', 'thank '),
)

The above methods are valid. For details, refer to your choice.

Because objects returned by patterns () can be added, when you encounter path prefixes of multiple views modules, you can manage your path matching in the following way: FromDjango. conf. urls ImportPatterns, include, url

Urlpatterns = patterns ('books. view ',
Url (R' ^ hello/$ ', 'Hello '),
Url (R' ^ search/$ ', 'search '),
Url (R' ^ contact/$ ', 'Contact '),
Url (R' ^ contact/thanks/$ ', 'thank '),
)

Urlpatterns + = patterns ('weblogs. view ',
Url (R' ^ hello/$ ', 'World '),
) Use the group operation of regular expressions to pass the parameter regular expression to views. You can use () to indicate a successfully matched group. You can also use backward reference \ 1, \ 2... \ n indicates different groups, and the expression indicates repeated matching strings. If groups is not required, a match object is returned. You can also name a group in python (? P <year> \ d {4}), meaning the group name is year, the match is four digits. Because there are two types of numbers: Named group and unnamed group, we can pass the parameters to the view function in two ways: 1. if the group is not named, values are passed in sequence # views. py
DefCount (Self, A, B ):
....
# Urls. py
(R' ^ num/(\ d {4})/(\ d {2})/$ ', count ),
# Result
# For requests/num/1234/78, the call is count (1234, 78) 2. The name group is passed in dictionary mode # urls. py
(R' ^ num /(? P <B> \ d {4 })/(? P <a> \ d {2})/$ ', count ),
# Result
# For requests/num/1234/78, the calling result is count (B = 1234, a = 78). By comparison, using a naming group has a greater advantage and makes the code clear at a glance, you don't have to worry about Parameter order errors. It is better not to mix named groups and non-named groups. Although Django does not report errors, it is not very good, you know. The following describes the url matching process: 1. if the name group is included, the dictionary parameter 2 is preferred. other non-naming groups will be passed to the remaining parameters in order 3. other options in the url will be passed in dictionary mode # urls. py
Urlpatterns = patterns ('',
# The third option value can be used to pass some additional information and make the Request Path concise.
# Otherwise, sometimes the request link contains too many parameters.
(R' ^ foo /(? P <a> \ d {2}) $ ', count, {' B ': 43 }),
)
# Result
# For requests/num/12, the resulting call is count (12, B = 43). Of course, the default value can be used for the view function, if no matching value exists in the Request Path, the default value is called. Note: Generally, the default value should be set as a string, so that it is consistent with the type of the value matching the Request Path. Because they are all strings. Even if you match a mathematical string, you must use the int () function to convert the input string to a real integer. Here, I will review which part of the Request Path does django match? 1. Specify the Request Path www.example.com/myapp/fooonly matches the myapp/foopart. 2. Specify the Request Path www.example.com/myapp/foo? Name = david only matches the part of myapp/foo. given the Request Path www.example.com/myapp/foo?name=david only matches myapp/foothis part of the Request Path and does not contain the request GET or POST. Any request that matches successfully will run the same function, but this is not very good, it is better to use different processing methods for GET and POST. here we need to use the request object. We have also introduced that it contains a wealth of information.DefFoo (request ):
IfRequest. method = 'post ':
# Handle post...
# Need to redirect
ReturnHttpResponseRedirect ('/someurl /')
ElifRequest. method = 'get ':
# Handle get
# Just return response
ReturnRender_to_response('page.html ') uses Path Matching to dynamically construct the code on the function in the view: # views. py
DefSay_hello (Self, Person_name ):
Print'Hello, % s' % person_name

DefSay_goodbye (Self, Person_name ):
Print'Goodbye, % s' % person_name
# Urls. py
Urlpatterns = patterns ('',
(R' ^ say_hello/(\ w +) $ ', say_hello ),
(R '^ say_goodbye/(\ w +)/$', say_goodbye ),
)

The above two functions basically do the same thing, pass in a person's name, and then say hello.

Therefore, modify the matching rules and create a function to dynamically process the two tasks. # Views. py
DefGreet ( Self, Person_name, greeting ):
Print'% S, % s' % person_name

# Urls. py
Urlpatterns = patterns ('',
(R' ^ say_hello/(\ w +) $ ', greet, {'greeting': 'hello '}),
(R' ^ say_goodbye/(\ w +)/$ ', greet, {'greed': 'Goodbye '}),
You can see that the third option value in the url can input additional information to keep the Request Path concise. At the same time, this option value can also be passed into the model class, using delegation to make your view function more dynamic. You can also input the module name so that you do not need to write the module name to the render_to_response function. Note that when the name of the group is the same as that of the third option value, Django uses the third option value because it has a higher priority. Use closures and variable length parameters to reconstruct the views function. The following concepts are used: 1. function objects can also be passed as parameters. 2. closure, which can be simply understood as the function defined in the function 3. * args indicates a variable-length tuples parameter, also called a non-Keyword parameter. ** args indicates a variable-length dictionary parameter, which is also called a keyword parameter. Note the error message, keyword parameters must be placed on the rightmost refactoring example:DefMy_view1 (request ):
If NotRequest. user. is_authenticated ():
ReturnHttpResponseRedirect ('/accounts/login /')
#...
ReturnRender_to_response('template1.html ')

DefMy_view2 (request ):
If NotRequest. user. is_authenticated ():
ReturnHttpResponseRedirect ('/accounts/login /')
#...
ReturnRender_to_response('template2.html ')

DefMy_view3 (request ):
If NotRequest. user. is_authenticated ():
ReturnHttpResponseRedirect ('/accounts/login /')
#...
ReturnRender_to_response('template3.html ')
# The above three methods must be verified at the beginning, which is a bit repetitive.
# Add a new method below
DefRequires_login (view ):
DefNew_view (request, * args, ** kwargs ):
If NotRequest. user. is_authenticated ():
ReturnHttpResponseRedirect ('/accounts/login /')
ReturnView (request, * args, ** kwargs)
ReturnNew_view
# Use a closure to define the same verification part and return the corresponding function object.
# Implement different codes in the above three functions. You can remove all the verification items.
# In addition, you can change urls. py
FromDjango. conf. urls. defaultsImport*
FromMysite. viewsImportRequires_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 )),
) Use include () to reference other path configuration filesFromDjango. conf. urls. defaultsImport*

Urlpatterns = patterns ('',
(R' ^ weblog/', include ('mysite. blog. urls ')),
(R '^ photos/', include ('mysite. photos. urls ')),
(R' ^ about/$ ', 'mysite. views. about '),
) A project has a total of urls. py, and each app can also create its own urls. py, but all need to use the include () function to register in the project's urls. py file. In this way, use your project management. Note that '$' is not added to the matching expression using the include path, because Django's mechanism is to remove the part of the currently matched Request Path, the remaining parts are uploaded to the path configuration specified by include for matching. For example, for a request path/weblog/7000/, the matching part is weblog/7000/, and because weblog/matches successfully, the remaining part 7000/is passed into mysit. blog. in the urls file. When the Path Matching Using include () contains a regular group, this matching parameter is passed into all functions in the urlconf specified in include, no matter whether the function accepts this parameter, it is obviously easy to report errors, so this approach is not good. Similarly, if you use the third option parameter in the include Path Matching, it will also force all functions in the specified urlconf. Not very good either.

Publish by note

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.