Python's Django framework using the Getting Started Guide

Source: Internet
Author: User
Tags django server url forwarding ruby on rails
Preface





Traditional Web development methods often need to write tedious repetitive code, not only the page performance and logic implementation of the code mixed together, and the code is inefficient. For developers, choosing a powerful and concise development framework to assist with the intricacies of coding will help improve the efficiency of development. Fortunately, such a development framework is not uncommon, and the only thing that needs to be done is to choose the web framework that is precisely designed for developers.



Since the popularization of the concept of WEB design based on MVC hierarchy, choosing the appropriate development framework is undoubtedly the key factor of project success. Whether Struts, Spring, or other WEB frameworks appear, the goal is to help developers keep all coding work organized and enjoyable. In the field of dynamic language, Python, Ruby, Groovy and other languages in the Web development also gradually grow, set off a wave after wave of development craze. Faced with the growing popularity of Ruby on Rails and the fiery momentum of the campaign, more mature and lack of good programmers of the Python community has launched to contend with the Web development framework. After a comparison of the development framework of Python, I chose Python framework as the first choice of WEB development framework, the reason is that the new and concise Django development model and huge development potential.



In the following chapters, a complete example of the Django Framework Web development will give you a detailed explanation of the various elements and resources that are required in the development process for each level of MVC code authoring, and experience the efficiency and convenience that Django brings to Web developers through an instance.



About Django



Django is a high-level dynamic language framework for WEB development, originally originated in the US-Chicago Python user group, and the Adrian Holovaty with a journalistic background is the main developer of the Django framework. Led by Adrian, the Django team is committed to contributing a highly efficient Python development framework to WEB developers, and is licensed to developers free of charge under the BSD Open source agreement.



Django has a sophisticated template mechanism, object-relational mapping mechanism, and the ability to dynamically create a background management interface, and with Django, you can quickly design and develop WEB applications with MVC levels. To discourage developers from using the Django framework, first analyze Django's compelling features. In terms of entity mapping, Django's object-related mapping mechanism helps developers flexibly define the data model in Python classes, and Django has a rich dynamic database access API that can greatly simplify the tedious work of writing SQL statements. At the same time Django supports a variety of back-end databases, including Postgresql,mysql,sqlite,oracle. The Django URL distribution design is simple and beautiful, and does not produce a bunch of messy and incomprehensible characters in the link. With the Django extensible built-in template, you can encode the model layer, the control layer, and the page template completely independently. Django also has its own cache system and, if needed, can nest other cache frameworks as required by the developer.




Preparation before departure



Even though unfamiliar with the Python language, the start-up of the Django development process is not complicated for novices, and by using the Django framework to complete the following WEB application development, you can experience the agility and freedom that the Django framework gives developers in every step of the process.



Before you start, configure the Python and Django development environment first, the following example will be performed under the Windows operating system, slightly different from the environment variable configuration, compared to the development process under the Linux/unix operating system environment. At present, the latest version of Python is 2.5.1, after the official site python.org Download the installation package set up a python compiler run environment, next also need to add the Python installation path in the system environment variable path, in order to use Python at the command line to compile and run.



Django's current release is version 0.96, and its compressed package can be downloaded at the official site djangoproject.com. After extracting it into the Django directory, execute the Python setup.py install on the command line so that Django will be installed as a third-party module in the Python site-packages directory. Then add the path of the Django Bin directory to the environment variable path, which makes it easy to use the various commands provided by Django on the command line.




Start the Django Journey



In the following steps, you will use the Django framework to implement a fully compact Web application. An application instance creates a news bulletin board that allows users to add news categories and entries from the background and then display the news statistics on the front page. During the implementation of the application, you will step through the way Django is developed and the quick experience it brings.



To help developers achieve different functions, Django provides us with numerous development instructions, and most of the tedious operations are implemented by Django integrated in a simple command-line prompt. Now open a command prompt, go to the directory where you want to create the app, type the django-admin.py startproject News command, call the Django Console command to create a new project called News, At the same time, Django generates the following four separate files under the newly created News folder.



1. __init__.py
File __init__.py can indicate to the Python compiler that the content under the current folder is a Python engineering module.
2.manage.py
manage.py is a Python script file that works with the Django command-line tool django-admin.py to manage configuration of the established project.
3.settings.py
This is the Django project configuration file, and the project-related engineering module and database global configuration information are set in settings.py.
4.urls.py
The file urls.py is responsible for configuring address mappings for URLs and managing address formats for URLs.



When the new project is built, and if you can't wait to know what the new project looks like, Django has prepared a lightweight web server for you to test at any time during the development process. Developers can simply enter the project directory at the command prompt, type the command manage.py runserver, start the Web server to test the newly created project, and if it starts without errors, you will see a message like this: "Development server is Running at Http://127.0.0.1:8000/"indicates that the current project is already accessible via the 8000 port on this machine. Open the above address via the browser, and the initial page of the Django project shown in 1 will appear in front of the reader.
Figure 1. Django Project initial Page






Use the Ctrl+break or CTRL + C key combination at the command line to stop the Web server that the Runserver command starts. Of course, Django's own Web server is typically used during development testing, and when the Django project is actually released, the Django application can be deployed on Apache by loading the mod_python.so module to facilitate Web Access management and configuration.




Django's model definition



After the project is established, you can then write a Django application module. Type the command Python manage.py Startapp article, which generates a module named article under the current project, in addition to the __init__.py file that identifies the Python module in the directory, There are an additional two files models.py and views.py.



In the traditional web development, a large part of the workload is consumed in the database to create the required data tables and set table fields, and Django provides a lightweight solution for this. With Django's internal object-relational mapping mechanism, you can manipulate entities in a database table using the Python language, and the description of the entity model needs to be configured in file models.py.



In the current project, there is a need for two models models, corresponding to the list table and item table, to store the news classification and news items, each item item will have a foreign key to mark the attribution classification of the article. Below, open the Django-created models.py file, add the location as prompted in the file comment, and write the following code:
Listing 1. models.py file Model definition

class List (models.Model):
 title = models.CharField (maxlength = 250, unique = True)
 def __str __ (self):
  return self.title
 class Meta:
  ordering = ['title']
 class Admin:
  pass

The above Python code defines a List data table that stores news categories. The definition in the above model will be converted by Django into a structured query language that directly interacts with the database to create a data table, that is, a table named List is created. The two fields are the integer primary key id automatically generated by Django and the title of the VARCHAR type field with a maximum width of 250 characters, and a unique constraint is defined on the title field to ensure that the news category will not have the exact same name.

The function __str __ () is also defined in the List file, which returns the title field represented by the self string. In the Meta category, the list table is sorted in alphabetical order by title. In the Admin-like settings, Django is allowed to automatically generate the background management entry for Django superusers for the current Models. The keyword pass sets Django to generate the background management interface in the default way. This part can be seen in a later chapter, from which you can also experience the unique charm of Django. Next, add the Models corresponding to the news item Item, the code is as follows:
Listing 2. Adding news items Models

import datetime
class Item (models.Model):
 title = models.CharField (maxlength = 250)
 created_date = models.DateTimeField (default = datetime.datetime.now)
 completed = models.BooleanField (default = False)
 article_list = models.ForeignKey (List)
 def __str __ (self):
  return self.title
 class Meta:
  ordering = ['-created_date', 'title']
 class Admin:
  pass

The Models code corresponding to the Item data table is slightly more complicated, but not obscure. The code first introduces the datetime type, which is used to define the created_date field that represents the creation date of the article, and returns the current date of the system to set the default value of the field through Python's standard function datetime.datetime.now. In the ordering setting of record sorting, the symbol "-" means to arrange in reverse order of date, and if the article creation date is the same, then arrange in positive alphabetical order of title.

So far, the two data tables that need to be defined in the model part of the application have been created. The next step is to let Django deploy and generate the Models model that has been written in the database.


Django module deployment

In Django, the settings related to the global project need to be added in the configuration file settings.py. The author uses MySQL as the back-end database, and has created a database named django_news in MySQL. You need to set DATABASE_ENGINE = "mysql" and DATABASE_NAME = "django_news" in the corresponding locations in the settings.py file.

It should be noted here that if you use a SQLite database, Django can automatically create a new database in SQLite according to the name of the database, and in MySQL, PostgreSQL or other databases, you need to first create a database corresponding to the set name. When using the MySQL database, you need to install MySQL's Python link library MySQLdb-1.2.1. This module can be downloaded from the site http://sourceforge.net/projects/mysql-python/. The currently supported Python version is 2.4, so The use of the MySQL database requires development and operation in the Python environment of version 2.4.

The following two contents of DATABASE_USER and DATABASE_PASSWORD require users to fill in the user name and password to access the database according to the settings of the machine. If the database is installed on another machine or the listening port of the database is changed, you also need to set the DATABASE_HOST address and DATABASE_PORT item. The Mysql database used by the author is set to:

DATABASE_USER = 'django'
DATABASE_PASSWORD = 'django_password'

In order for Django to recognize the application module added by the developer, in the INSTALLED_APPS section of the settings.py file, you need to define the list of applications loaded by the Django project. By default, some of the self-contained modules required for running the Django project have been added to the list. We also need to add the application module news.article just written to it, and add the django.contrib.admin application module that comes with Django. The modified code is as follows:
Listing 3. Add the required modules

INSTALLED_APPS = (
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.admin',
 'news.article',
)

After adding the admin module, you can't use Django's admin background management interface immediately. You need to open the urls.py file in the root directory of the News project, and remove the # comment after "# Uncomment this for admin:" to make Django target the management interface URL Go to "(r '^ admin /', include ('django.contrib.admin.urls'))," available, so that when accessing the admin module, Django can successfully resolve the access address and move to the background management interface.

When the configuration file is changed, you can execute the manage.py syncdb command at the command prompt of the News project. Django will automatically complete the ORM database mapping work according to the definition of the model, shielding the details of the underlying database and the writing of SQL queries.

The time to show the charm of Django has arrived, and the Django framework will allow developers to start a magical experience. With the scrolling prompt after the command is executed, Django has automatically created the corresponding tables and fields in the database based on the mapping file we just defined in the models. At the same time when the command is executed, the user will be prompted to create a "superuser" account to log in to the background management interface automatically created by Django to manage the model. The command prompt 2 to update the database table synchronously when the instruction is executed is shown as follows:
Figure 2. Django commands update database tables synchronously
The best way to maintain learning motivation is to find a little sense of accomplishment at any time. Let's take a look at what these steps have done. Use the command manage.py runserver again to start the web server that comes with Django, visit the address http://127.0.0.1:8000/admin/ in the browser, log in using the account and password of the superuser user just created, 3 The beautiful Django background management interface appears in front of you.
Figure 3. Django automatically generates a background management interface based on the model
In the admin management interface, each model module that has been defined in the application is displayed. When you click to view, a list of database objects existing in the models is displayed. The background management interface provided by Django is convenient for users to directly change or add database fields. Next, we click "Add" next to the "Lists" item to add a new news category. Type "Sports News" or other categories you like in the title field and save. Then click "Add" in the "Items" item, fill in the first item of the news, each Item item corresponds to a category item in the List, as shown in the interface 4 for adding Item, due to the association between the tables , Django's Item management interface will automatically generate drop-down options for the added List category.
Figure 4. The interface for adding news items
Django's convenient background management interface saves a lot of time for web developers. At present, only the default background management method of Django is used. Developers can also refer to the user manual provided by Django to further customize and personalize the background.


Implement Django's control layer and presentation layer

At this point, the model layer in the Django project has been processed. The next thing to do is how to use the code to interact with the fields defined in the models. This is the View part in Django. Slightly different from the traditional MVC layered definition, in Django, the function of View is to respond to page requests and logical control, and the content of the page is represented by Django's Template template. We can understand Django's View as a Python function that implements various functions. View is responsible for receiving the URL forwarding and response processing defined in the URL configuration file urls.py. When Django receives the request, it calls the corresponding View function to complete the function. The code of the views.py file in the module is defined as follows:
Listing 4. Views.py code definition

from django.shortcuts import render_to_response
from news.article.models import List

def news_report (request):
 article_listing = []
 for article_list in List.objects.all ():
  article_dict = {}
  article_dict ['news_object'] = article_list
  article_dict ['item_count'] = article_list.item_set.count ()
  article_dict ['items_title'] = article_list.title
  article_dict ['items_complete'] = article_list.item_set.filter (completed = True) .count ()
  article_dict ['percent_complete'] =
    int (float (article_dict ['items_complete']) / article_dict ['item_count'] * 100)
  article_listing.append (article_dict)
 return render_to_response ('news_report.html', {'article_listing': article_listing})

This is a concise Python code, let's see what work Django functions do in this code:

The List.objects.all method returns all the records in the news list. Django can convert the corresponding SQL statements according to the back-end database, execute them in the back-end database and return the query results.
Each article has an item_set attribute, which represents each item in the news item. If you need to set query conditions, you can also use the item_set.filter method to return item items that meet specific requirements.
The render_to_response function returns the HTML page specified by the browser. The page is a Django template, which is responsible for displaying the requested page content.
In the code of the view section, the page display template has been specified as news_report.html. In fact, it is a very convenient thing to create a template in the Django project. Let's create this template page in the article directory, first create a new folder named templates, and then create the required news_report.html in this template directory Template file, the template code is as follows:
Listing 5. news_report template code

 
  
   
   
  
  
  
News statistics list
 
{% for list_dict in article _listing%}
  
 
   
News classification: {{list_dict.items_title}}
 
   
Number of news: {{list_dict.item_count}}
 
   
Number of news published:
      {{list_dict.items_complete}} ({{list_dict.percent_complete}}%)
 
  
 
{% endfor%}
  


In general, Django ’s template code does not look much different from ordinary HTML code, but it adds Django-specific template tags. These tags allow developers to add page logic to Django templates, such as the render_to_response function in views.py The returned database result set is displayed on the page. Django-specific tags start with "{%" and end with "%}" in the template page. Variables embedded in Django templates start with "{{" and end with "}}".

In the template code above, the tags {% for news_dict in article_listing%} and {% endfor%} are used. Such a tag tells the Django template processing mechanism to cycle out the item items in the news and output them on the page. Inside the for loop, the value of the corresponding data item field in the View is obtained through the attribute of article_listing and the Title of each news item and the news are displayed. The number of item items in

When the Django View and Template are ready, the following only needs a few steps to tell Django to store the template location of the project application. This requires setting the TEMPLATE_DIRS item in the configuration file setting.py. Adding the storage path of the template file "news_report.html" in this example allows Django to return the result set of the View processing through the specified template. According to the structure of this example application, the content of the TEMPLATE_DIRS parameter is set to:

Copy the code The code is as follows:

icle / templates',
Don't forget that Django needs to add a comma at the end of the path. Next, you only need to set the URL forwarding address when accessing the article. Open the urls.py file, and add the following statement in the next line of the forwarding address managed by the admin background:

Copy the code The code is as follows:

(r '^ report / $', 'news.article.views.news_report'),
At the end of the paragraph here, a comma is also needed to mark the end of the paragraph. As you can see here, Django's URL forwarding design is very simple. The forwarding request corresponding to the view in the configuration file urls.py consists of two parts. The first part follows the regular expression to specify the matching URL address. The second part It is a function corresponding to processing forwarding request in View.

After completing these steps, you can start the Django server again at the command prompt, take a look at the results of the above efforts, open the link http://127.0.0.1:8000/report/ in the browser, you will see the news list Back to the interface. The page displays the classified statistics of all the news that has been added to the database. It is worth mentioning that Django templates support multiple layers of nesting, and each layer can use DIV + CSS to complete the layout, which can easily make the site pages follow a unified style and look beautiful.

Throughout the above process, a preliminary introduction to web development using Django is given. The Python code written in the application is only a few dozen lines. Compared with other development languages, Django is very convenient and practical. Finally, let's review what work Django has helped us do:

Two data tables for storing news categories and news items were established through Django's object-relational mapping model, and synchronized to the database with the syncdb command.
With the help of Django's management function, a beautiful and practical background management interface is generated in the application.
Using Django functions and tags, I wrote a view function module and a template for displaying data results.
Conclusion

The emergence of the Django development framework makes all the work in this example simple and orderly, pleasing to the eye. With the continuous development of the Django development framework, more new features will be gradually added to the framework system. It is no exaggeration to say that Django has gradually grown from a potential competitor of ROR to a Python framework that can be opposed to it. If the gap with the Ruby framework ROR, perhaps Django is currently the most lacking is the large user base of ROR.

After reading this article, readers intend to step into the wonderful world of Django step by step, you can read more development documents on the official Django site www.djangoproject.com, subscribe to the Django mail discussion group on the Google Group, or follow the official Django The tutorial guide is to learn and start a journey of letting the thoughts soar freely. I believe that in this process, it is not only a novel experience developed using Django.

I hope that more readers will use the Django framework, and that more people will follow the development of Django together, and even participate in the development of Django projects to contribute to the open source community. Looking forward to the rapid development of Django tomorrow, and the Rails framework implemented by Python will have a brilliant future!

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.