Django Study Notes (12): Advanced view (below)

Source: Internet
Author: User

1. built-in common view functions of Django

The previous section details general views, which are presented, extended, and summarized one by one.

Common View functions can be divided into the following:
1. Redirect and render pages
2. display the list and specific content
3. Archiving
4. add, delete, query, and modify objects

They are mainly used to improve development efficiency, provide a set of functional modules, or provide these functional interfaces.

Ii. Static General View

I may do this when I am not familiar with general views about processing static pages.

1 url: 2 urlpatterns = patterns ('', 3 (R' ^ common/about/$ ', 'login. views. about'), # about us 4) 5 views: 6 def about (request): 7 return render_to_response ('common _ operate/about.html '')

If there are a lot of static pages, I think this is not the way to write. A common view can be used in Django view functions as follows:

1 URL: 2 from django. views. generic. simple import direct_to_template3 urlpatterns = patterns ('', 4 (R' ^ common/about/$ ', direct_to_template, {'template': 'common _ operate/about.html '}), # About this website 5)

In this way, you don't need to write the view function. Django has automatically handled it for us. Because the direct_to_template view obtains the relevant information required for rendering the view from the parameters. The English meaning is clear. direct (direct) _ to (to) _ template (template )......

Iii. General View of Objects

The object here is the object model in the model. The general view of the object refers to the processing of data in the database, which is the most common part, for example, generate a list of Model objects and a detailed view.
Object List View:

 1 URL: 2 from login.models import New 3 from django.views.generic import list_detail 4 new_info={ 5     "queryset":New.objects.all(), 6 } 7  8 urlpatterns = patterns('', 9    (r'^test/new_test/$',list_detail.object_list,new_info),    10 )

If there is another template, you may want to use "template" to tell the object_list view function which template to use, but the object_list view is general-purpose. Are you sure you want to change it to a private one?

When Django does not give a template, it will use the object name to export one, such as login/new_list.html. loginis the appname, and new_list.html is the lowercase form of the data model New followed by _ list. As follows:

Note that this template will be rendered according to the object_list variable contained in the context, as shown below:

1 <ul>2 {% for new in object_list %}3 <li>{{new.title}}</li>4 {% endfor %}5 </ul>

It looks Cool.

This is a bit unfriendly, because in the template, we don't know what the object_list is. Here we can extend it:

1 URL:2 ....3 new_info={4     "queryset":New.objects.all(),5     "template_object_name":"new",6 }7 ....

Then, Change {% for new in object_list %} in the template to new_list.
In the templateTemplate_object_nameAppend_ ListTo create a variable name that represents the list items.

4. Add additional Context

1. My implementations

In layman's terms, there are two Database Data Rendering tasks on a page. A good solution is to load data using Ajax. For example:

We load the "Post message" page to the "message list" page. The effect is as follows:

The implementation is as follows:

1 URL: 2 urlpatterns + = patterns ('', 3 (R' ^ messages/message_list/$ ', 'login. msg. msg_list_page '), # comment list 4 (R' ^ msg/send_msg/$', 'login. views. send_msg '), # post message 5)

The URL for posting a message only provides a path, and its view function only renders one (no data) page. If you are in trouble, you can use a general view to implement a static page.

Here, the HTML code is not displayed, but the above interface is provided. Here, the js Code is written:

1 <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd 2 

However, this is only a single page. We need to use Jquery's Ajax to load it to the "message list" page, in the "message list", we can first write a <div class = "load_send_msg"> </div>, and then write ajax on the base.html page or the message list page as follows:

1 // Ajax load page 2 $ (document ). ready (function () {3 $ ('. add_msg '). load ('/msg/send_msg/'); // Add a message --> message list 4 })

In this way, the above results are achieved.

Thinking: I always think the code is too cumbersome. If both pages need to load data, I have to write more view functions for data processing, here, Django provides an additional Context that may reduce the workload.

2. Add additional Context

For example, if you want to display the "Notification" list in the "news" list, you can do this:

1 URL: 2 new_info = {3 "queryset": New. objects. all (), 4 "template_object_name": "new", 5 'extra _ context': {'note _ list': note. objects. all ()}, # notification 6}

All common views have an additional optional parameter.Extra_context. This parameter is a dictionary data type that contains additional objects to be added to the context of the template. In this way, note_list is a template variable.
Note. If multiple extra_context are put, only the last one is used, because the previous one is overwritten by the later one.

Hidden bugs: If you delete a data in an additional Context, the page will not change, and the refresh will not change. You can only restart the server.
Cause:Extra_contextContains database query problems. objects. put all () in URLconf and it will only run once (when URLconf is loaded for the first time). When data is added or deleted or changed, the general view will not reflect the changes.

Optimization:InExtra_contextUse a callback instead of a variable. AnyExtra_contextThe callable object (such as a function) is executed before each view rendering (rather than only once ).

1 def get_note (): 2 return Note. objects. all () 3 4 new_info = {5 "queryset": New. objects. all (), 6 "template_object_name": "new", 7 'extra _ context': {'note _ list': get_note}, # notification 8}

Or, in factPublisher. objects. allIt can be called:

1 new_info = {2 "queryset": New. objects. all (), 3 "template_object_name": "new", 4 'extra _ context': {'note _ list': note. objects. all}, # notification 5}

Note:Note. objects. allThere are no parentheses. This indicates that this is a reference to a function and it is not actually called (a general view will call it during rendering ).

5. Use Function packaging to process complex data filtering

You can retrieve the data by id or other methods. However, http://djangobook.py3k.cn/2.0/chapter11/example is more interesting.

 

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.