Implement the control layer and performance Layer of Django

Source: Internet
Author: User
Tags django server url forwarding

The View section in Django is how to use code to interact with fields defined in models. Unlike the hierarchical definition of traditional MVC, in Django, the View function is to respond to page requests and control the logic, the page content is represented by the Django Template. We can understand Django's View as a Python function that implements various functions. View accepts the URL configuration file urls. py defines the URL forwarding and Response Processing. After Django receives the request, it calls the corresponding View function to complete the function. views in the article module. the code of the py file is defined as follows:

Views. py Code definition

 
 
  1. from django.shortcuts import render_to_response   
  2. from news.article.models import List   
  3.  
  4. def news_report(request):   
  5.  article_listing = []   
  6.  for article_list in List.objects.all():   
  7.    article_dict = {}   
  8.    article_dict['news_object'] = article_list   
  9.    article_dict['item_count'] = article_list.item_set.count()   
  10.    article_dict['items_title'] = article_list.title  
  11.    article_dict['items_complete'] = article_list.item_set.filter(completed=True).count()   
  12.    article_dict['percent_complete'] =  
  13.         int(float(article_dict['items_complete']) / article_dict['item_count'] * 100)   
  14.    article_listing.append(article_dict)   
  15.  return render_to_response('news_report.html', { 'article_listing': article_listing })   

This is a concise Python code. Let's take a look at what the Django function has done in this Code:

The List. objects. all method returns all record items in the news List. Django can convert them to corresponding SQL statements based on the background database, execute the statements in the background database, and return the query results.

Each article has the item_set attribute, representing each item in a news item. If you need to set query conditions, you can also use the item_set.filter method to return items that meet specific requirements.

The render_to_response function returns the HTML page specified by the browser. The page is a Django Template that displays the requested page content.

The page display template news_report.html has been specified in the viewobject code. Template file. The template code is as follows:

News_report template code

 
 
  1. < Html>
  2.  < Head>
  3. < Meta Http-equiv="Content-Type" Content="Text/html" />
  4. < Title>News statistics list</Title>
  5.  </Head>
  6.  < Body>
  7. < H1>News statistics list</H1>
  8. {% For list_dict in article_listing %}
  9. < Ul>
  10. < Li>News classification: {list_dict.items_title }}</Li>
  11. < Li>News count: {list_dict.item_count }}</Li>
  12. < Li>Number of published news:
  13. {List_dict.items_complete }}( {list_dict.percent_complete }}%)</Li>
  14. </Ul>
  15. {% Endfor %}
  16.  </Body>
  17. </Html>

In general, the template code of Django does not look very different from the ordinary HTML code. It only adds a specific template tag of Django, which allows developers to add page logic for the Django template. For example, views. the database result set returned by the render_to_response function in py is displayed on the page. The Django-specific tag starts with "{%" on the template page and ends with "%. Variables embedded in the Django template start with "{" and end.

In the preceding template code, {% for news_dict in article_listing %} and {% endfor %} are used }. This tag tells the Django template processing mechanism to cyclically retrieve the items in news and output them to the page. Inside the for loop, get the value of the corresponding data item field in View through the attribute of article_listing, and display the Title of each news item and the number of item items in news.

When both the View and Template of Django are properly configured, you only need to configure the Template location of the Django Storage Project Application in the following steps. This requires setting the TEMPLATE_DIRS item in the configuration file setting. py. In this example, add the storage path of the template file "news_report.html" to allow Django to return the result set for View processing through the specified template. According to the application structure in this example, the content of the TEMPLATE_DIRS parameter is set:

& Apos;./article/templates & apos ;,

Do not forget to add a comma at the end of the path to Django. Next, you only need to set the URL redirection address when accessing article. Open the urls. py file and add the following statement to the next line of the redirection address managed by the admin Background:

(R & apos; ^ report/$ & apos;, & apos; news. article. views. news_report & apos ;),

At the end of a paragraph, a comma is also required to mark the end of the paragraph. Here we can see that Django's URL forwarding design is very simple, in the configuration file urls. in py, view-specific forwarding requests are composed of two parts. The first part follows the regular expression to specify the matched URL address, and the second part is the function for processing the forwarding request in View.

After completing these steps, you can start the Django server again at the command prompt and check the results of the above efforts. Open the link http: // 127.0.0.1: 8000/report/in the browser /, the return page of the News list is displayed. The classification statistics of all news added to the database are displayed. It is worth mentioning that the Django template supports multi-layer nesting, and each layer can be laid out using DIV + CSS, so that the site pages can follow a unified style and look elegant and generous.

In the above process, we will give a preliminary introduction to using Django for Web development. The Python code written in the application is dozens of lines. Compared with other development languages, Django is very convenient and practical. let's review what Django has helped us do:

Through the object-link ing model of Django, two data tables are created to store news categories and news items, and synchronized to the database using the syncdb command.

With the help of Django's management function, a beautiful and practical background management interface is generated in the application.

The view function module and the Template for displaying data results are compiled using Django functions and labels.

Edit recommendations]

  1. Deployment of Django Module
  2. Solve the problem that Eclipse cannot debug the configuration of the agent program
  3. Detailed description of client configuration on SVN server and Eclipse
  4. List of Eclipse platform extension points
  5. Use Eclipse to develop PHP Projects

Related Article

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.