Python's Django framework uses the Getting Started guide _python

Source: Internet
Author: User
Tags postgresql sqlite sqlite database python script url forwarding ruby on rails django tutorial in python

Objective

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 code writing efficiency is not high. For developers, the choice of a powerful and simple development framework to assist in the implementation of complex coding work, will be a great help to improve the efficiency of development. Fortunately, such a development framework is not uncommon, and all that needs to be done is to choose the web framework tailored to the developer.

Since the popularization of WEB design concept based on MVC hierarchy, choosing the appropriate development framework is undoubtedly the key factor to the success of the project. Whether it's Struts, Spring, or any other WEB framework, the goal is to help developers keep all the coding work in Apple-pie order, pleasing to the eye. In the field of dynamic language, Python, Ruby, Groovy and other languages in the Web development is also gradually growing, a wave of waves of development boom. The Python community, a more mature and talented programmer, has launched a Web development framework to contend with in the face of Ruby on Rails's increasingly popular propaganda and fiery momentum. After comparing the development framework of Python, the author chooses the Python framework Django as the first choice of the Web development framework, and the reason is that the new and concise development model of Django and the great development potential.

In the following sections, a complete Django framework Web Development example is used to explain in detail the various elements and resources required during the development process of the MVC hierarchy code, and to experience the efficiency and convenience that Django brings to Web developers through an instance.

To elaborate on Django

Django is a high-level dynamic language framework applied to WEB development, originally from the United States of Chicago, the Python user group, 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 and perfect Python development framework for WEB developers, and is licensed to developers for free use under the BSD Open source protocol.

Django has a well-established template mechanism, object-relational mapping mechanism, and the ability to dynamically create a background management interface, using Django to quickly design and develop a WEB application with an MVC hierarchy. To discourage developers from using the Django framework, first analyze the compelling features of Django. In terms of entity mappings, Django's object-related mapping mechanism helps developers flexibly define data models in the Python class, and Django has a full-featured dynamic database access API that can greatly simplify the intricacies of writing SQL statements. Django also supports a variety of backend databases, including postgresql,mysql,sqlite,oracle. Django's URL distribution design is very simple and beautiful, and will not produce a large string of messy and incomprehensible characters in the link. With Django's 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, which, if needed, can be nested with other cache frames as required by the developer.


the preparation before departure

Even if you are unfamiliar with the Python language, the initial process of Django development is not complicated for novices, and by using the Django framework to do the following WEB application development, you can learn from each step of the process that the Django framework gives developers agility and freedom.

Before you start, configure the Python and Django development environments, and the following example will be done under Windows operating systems, slightly different from the development process in the Linux/unix operating system environment, only in terms of environment variable configuration. The latest version of Python is 2.5.1, which builds Python's build-and-run environment after the official site python.org downloading the installation package, and then adds the Python installation path to the system environment variable path to compile and run using Python at the command line.

Django's current release is version 0.96, and its compression pack can be downloaded at the official site djangoproject.com. Unpack into the Django directory and execute Python setup.py install on the command line so that Django is installed as a third-party module in the Python site-packages directory. The path to the bin directory in Django is then added to the environment variable path, which makes it easy to use the various commands that Django provides on the command line.


start the Django journey

In the following steps, you will implement a complete and compact Web application using the Django framework. The 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 in the front-end page. The implementation of the application will introduce the Django development approach and the quick experience it brings.

To help developers achieve different functions, Django provides us with a number of development directives, most of which are integrated by Django in a neat command-line prompt. Now open the command prompt, go to the directory where you want to create the application, type django-admin.py Startproject news, and invoke the Django Console command to create a new project called News. Meanwhile, Django also 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 contents of the current folder are Python engineering modules.
2.manage.py
manage.py is a python script file that, in conjunction with the Django command-line tool django-admin.py, can be used to manage the configuration of established projects.
3.settings.py
This is the configuration file for the Django project, and the engineering-related engineering modules and database global configuration information are set in settings.py.
4.urls.py
File urls.py is responsible for configuring address mappings for URLs and for managing URL formats.

When the new project is built, 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 simply enter the engineering directory at the command prompt, type the command manage.py runserver, start the Web server to test the newly created project, and if the startup is not wrong, you will see the following message: "Development server is Running at Http://127.0.0.1:8000/"indicates that the current project is already accessible through local port 8000. Open the above address through the browser, as shown in Figure 1, the Django Project initial page will appear in front of the reader.
Figure 1. Django Project Splash Page

Use the Ctrl+break or CTRL + C key combination on the command line to stop the Web server where the Runserver command starts. Of course, Django's Web servers are typically used in the development of tests, and when the Django project is actually released, it is possible to deploy the Django application 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, the Django application module can then be written. Type the command Python manage.py Startapp article, which generates a module named article under the current project, in addition to identifying the __init__.py file for the Python module, There are additional two files models.py and views.py.

In traditional web development, a large portion of the workload is consumed in creating the required data tables and setting table fields in the database, and Django provides a lightweight solution for this. With the help of the object-relational mapping mechanism within Django, the entities in the database tables can be implemented in Python language, and the description of the entity model needs to be configured in the file models.py.

In the current project, need to have two models models, corresponding to the list table and item table, to store news classification and news entries, each item item will have a foreign key to mark the attribution of the article classification. Next, open the models.py file that Django creates, and follow the instructions in the file note to add the location, 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 Python code above defines a list of stored news classifications, defined by Django as a structured query language that interacts directly with the database to create a datasheet that creates a table named list. The two fields in the table are the integer primary key IDs that Django automatically generates and the varchar type field with a maximum width of 250 characters, and a uniqueness constraint is defined on the title field to ensure that the news classification does not have exactly the same name.

function __str__ () is also defined in the list class file to return the title field represented by the self string. In the class meta, the list table is sorted in the title alphabetical order. In the settings for Class admin, Django is allowed to automatically generate the background management portal for Django super users for the current models model, and the keyword pass setting django will generate the admin interface by default. This part can be seen later in the chapter, and it can also realize the unique charm that Django brings. Next, add the models model for the news item item, as shown in the following code:
Listing 2. Add News item Models Model

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 for the item datasheet is slightly more complex, but not obscure. The code first introduces the datetime type, which defines the Created_date field that represents the date the article was created, and sets the default value for the field by returning the system's current date through the Python standard function Datetime.datetime.now. In the ordering setting for record sorting, the symbol "-" is arranged in reverse order by date, and if the article creation date is the same, then the alphabetical order of title is followed.

So far, two of the data tables that need to be defined in the Model section of the application have been created, and the next step is to have Django deploy and build the models model already written in the database.


deployment of Django modules

In Django, project-related settings need to be added to the configuration file settings.py. The author uses MySQL as the background database, and has created a database named Django_news in MySQL. You need to set the corresponding position in the settings.py file Database_engine = "MySQL" and database_name = "Django_news".

Note here that if you use the SQLite database, Django can automatically create a new database in SQLite based on the name of the database, and in MySQL, PostgreSQL, or other databases, you need to create a database that corresponds to the setting name first. When using the MySQL database, you need to install additional MySQL Python link library MySQLdb-1.2.1, which can be downloaded at the site http://sourceforge.net/projects/mysql-python/, The Python version currently supported is 2.4, so using the MySQL database requires a 2.4 version of the Python environment to be developed and run.

The next Database_user and Database_password two items require users to fill out the user name and password to access the database based on their local settings. If the database is installed on another machine or if you change the listener port for the database, you also need to set the Database_host address and Database_port entry. The MySQL database that I use is set to:

Database_user = ' Django ' 
database_password = ' Django_password '

To enable Django to identify the application modules added by the developer, in the Installed_apps section of the settings.py file, you need to define a list of applications that the Django project loads. By default, some of the self-contained modules required to run the Django project are already added to the list. We also need to add the application module news.article that we just wrote, adding Django's own django.contrib.admin application module, and the modified code looks like this:
Listing 3. To 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 will not be able to use the Django Admin interface immediately, you need to open the urls.py file under the news engineering root directory, and remove the # comments after the # uncomment this for admin: "(R ' ^admin/', include (' Django.contrib.admin.urls ')"), which allows Django to turn to the URL of the admin interface, "available, When you access the Admin module, Django can successfully parse the access address and turn to the backend admin interface.

When the configuration file changes are complete, the manage.py syncdb directive can be executed at the News engineering command prompt. Django automatically completes the ORM database mapping based on the definition of the model, masking the underlying database details and compiling the SQL queries.

The time has come to show Django's charms, and the Django framework will allow developers to start a magical experience. With the scrolling prompts 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 models. Command execution will prompt the user to create "Superuser" accounts, to login Django automatically create a good background management interface to face the Model Management. The command prompt to synchronize the Update database table when the instruction executes is as shown in Figure 2:
Figure 2. Synchronize Update database table when Django instruction executes

The best way to stay motivated is to find a little sense of accomplishment at any time, and here's a look at what these steps are doing. Once again, use the command manage.py Runserver to launch the Django self-contained Web server, access the address http://127.0.0.1:8000/admin/in the browser, and log in using the account and password of the Superuser user you just created. As shown in Figure 3, the beautiful Django Admin interface appears in front of you.
Figure 3. Django based on the model automatically generated by the background management interface

The admin interface shows the various models modules already defined in the application, and when clicked, displays a list of database objects that exist in the models. Django provides a background management interface to make it easy for users to change or add database fields directly, and then click "Add" next to "Lists" to add a new news category. Type "Sports News" or other categories you like in the Title field to save it. Then click "Add" in the "Items" item, fill in the first entry of the news, each item item corresponds to a category item in the list, add the item's interface as shown in Figure 4, because the association between the tables is set, The Django Item management interface automatically generates the Drop-down options for content that has been added to the list category.
Figure 4. Add a news entry interface

Django's Convenient backend admin interface saves a lot of time for web developers, and currently uses only the Django default admin style, and developers can further customize and personalize the background with Django's user manual.


implementing Django's control layer and presentation layer

To get here, the model layer in the Django project has been processed, and the next thing to do is how to interact with the fields defined in the models with code, which is the view part of Django. Slightly different from the traditional MVC hierarchy definition, the function of view in Django is to respond to page requests and logic control, while the presentation of page content is done by the Django template template. We can interpret the Django view as a Python function that implements various functions, View is responsible for accepting and responding to URLs defined in URL profile urls.py, and when Django receives a request and calls the corresponding view function to complete the function, the views.py file code in the article 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 '] * 
  article_listing.append (article_dict) return 
 render_to_response (' news_report.html ', { ' Article_listing ': article_listing})

This is a neat Python code, so let's take a look at what the Django function does in this piece of code:

    • The List.objects.all method returns all the entries in the News list, which can be converted from a background database to a corresponding SQL statement, executing in the background database, and returning the query results.
    • Each article article has a Item_set attribute that represents each item item in a news item. If you need to set query criteria, 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, and the page is the Django template template, which is responsible for displaying the requested page content.

In the code in the View section, the page display template has been specified as news_report.html. In fact, creating a template in a Django project is a handy thing to create in the article directory, creating a new folder named templates, and creating the desired news_ in this template directory. report.html template file, the code for the template is as follows:
Listing 5. News_report Template Code

 
 

In general, Django template code does not look much different from normal HTML code, but adds Django-specific template tags that allow developers to add page logic to Django templates, such as views.py render_to_ The database result set returned by the response function is displayed on the page, and the Django-specific label starts with "{%" in the template page and ends with "%}". The variable that embeds the Django template starts with "{{" and ends with "}".

In the template code above, the tag {% for news_dict in article_listing%} and {% ENDFOR%} are used. This tag tells the Django template processing mechanism to loop out the item output from news in the page, within the For loop, through the Article_ Listing's properties get the value of the corresponding data item field in view and display the title title of each news item and the number of item items in news.

When Django view and template are ready, only a few steps are required to tell the Django Storage engineering application of the template location, which requires setting the Template_dirs item in the configuration file setting.py. Adding a storage path to the template file "news_report.html" In this example allows Django to return the result set that handles the view to the specified template. According to the structure applied in this example, the contents of the Template_dirs parameter are set to:

Copy Code code as follows:
Icle/templates ',

Don't forget that Django needs to add a comma at the end of the path. The next step is to set the URL of the access article to the address. Open the urls.py file, and add the following line to the next row of the admin-managed steering Address:

Copy Code code as follows:
(R ' ^report/$ ', ' news.article.views.news_report '),

At the end of the paragraph, you also need to mark the end of the paragraph with commas. As you can see here, the Django URL forwarding design is very concise, in the configuration file urls.py in the view of the forwarding request is composed of two parts, the first part of the regular expression to specify the matching URL address, the second part of the view to handle the forwarding request function.

By completing these steps, you can start the Django server again at the command prompt, look at the results of these efforts, open the link http://127.0.0.1:8000/report/in the browser, and you will see the return interface of the news listing. The page shows the category statistics for all news that have been added to the database. It is worth mentioning that Django templates support multi-layer nesting, and each layer can be used div+css way to complete the layout, you can easily make the site page to follow the unified style, looks elegant.

In the whole process, a preliminary introduction is made to the use of Django for Web development. The Python code written in the application is dozens of lines, and the other development language, Django is very handy and useful, and finally, let's look back at what Django has helped us with:

    • The Django Object-relational mapping model establishes two data tables for storing news classifications and news items, and updates them to the database synchronously with the SYNCDB command.
    • The use of Django management features in the application generated a beautiful practical background management interface.
    • Use the Django functions and tags to write the view function module and the template template that displays the results of the data.

Conclusion

The advent of the Django Development Framework has made this example all of this work more concise and orderly. As the Django development framework continues to evolve, more new features will be added to the framework system gradually. It's no exaggeration to say that Django has grown from the potential competitor of ROR to the Python framework that can be opposed to it. If the gap with the Ruby framework Ror, perhaps Django is currently the most missing is the Ror large user community.

If you read this article, the reader is going to step into Django's wonderful World, read more development documents on the Django official site www.djangoproject.com, subscribe to the Django Mail discussion group on Google Group, or follow the official Django Tutorial guide and start a journey to free your mind, believing that the process is not just a novelty experience with Django development.

Hopefully more readers will use the Django framework, and hopefully more people will come together to focus on Django's development and even participate in Django's project development, contributing to the open source community. Looking forward to Django's fast-growing tomorrow and the rails framework for Python's implementation will have a brilliant future!

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.