This article mainly introduces how to use the Python Django framework. This article is from the technical documentation on the IBM official website. For more information, see
Preface
Traditional Web development methods often need to write tedious and tedious repetitive code. not only is the page performance mixed with the logic implementation code, but the code writing efficiency is not high. For developers, selecting a powerful and concise development framework to help complete complicated coding work will greatly improve development efficiency. Fortunately, such a development framework is not uncommon. all you need to do is select the Web framework tailored to developers.
Since the popularization of the Web design concept based on the MVC layered structure, selecting a suitable development framework is undoubtedly a key factor for project success. The emergence of Struts, Spring, and other Web frameworks aims to help developers take care of all coding work in a well-organized and pleasing-to-the-eye manner. In the dynamic language field, languages such as Python, Ruby, and Groovy are also growing in Web development, setting off a wave of development boom. Faced with the increasing popularity of Ruby on Rails, the Python community, which is more mature and has no shortage of excellent programmers, has launched a Web development framework to compete with it. After comparing the development frameworks of Python, I chose the Python framework Django as the first choice for Web development frameworks, it is just a fancy to Django's novel and concise development model and huge development potential.
In the following chapter, we will use a complete Django framework Web Development example to explain in detail the various elements and resources required in the MVC coding process at various levels during the development process, using instances to experience the efficiency and convenience that Django brings to Web developers.
Elaborate on Django
Django is an advanced dynamic language framework applied to Web development. it was originally originated from the Python user group in Chicago, USA, and is a major developer of Django framework. Under the leadership of Adrian, the Django team is committed to contributing an efficient and perfect Python development framework to Web developers and authorizing them to use them freely under the BSD open source code protocol.
Django has a complete template mechanism, object relationship ing mechanism, and functions for dynamically creating backend management interfaces. with Django, you can quickly design and develop Web applications with MVC layers. To eliminate developers' concerns about using the Django framework, we should first analyze Django's compelling features. In terms of object ING, Django's object-related ing mechanism helps developers flexibly define data models in Python classes, and Django has a rich range of functions for dynamic database access APIs, it greatly simplifies the complex work of writing SQL statements. At the same time, Django supports a variety of background databases, including Postgresql, MySql, Sqlite, and Oracle. Django's URL distribution design is concise and elegant, and does not produce a large string of messy and incomprehensible characters in links. With Django's Extensible built-in template, you can encode the model layer, control layer, and page template completely independently. Django also has its own Cache system. if needed, you can also nest other Cache frameworks as required by developers.
Preparations before the start
Even if you are not familiar with the Python language, the start process of Django development is not complicated for beginners. you can use the Django framework to complete the following Web application development, in each step of the process, you can understand the agility and freedom that the Django framework gives to developers.
Before you start, you must configure the development environment of Python and Django. the following example will be performed in the Windows operating system, compared with the development process in the Linux/Unix operating system environment, environment variable configuration is slightly different. Currently, the latest version of Python is 2.5.1. after downloading the installation package from Python.org on the official site, set up the Python compiling and running environment. Next, add the Python installation path to the path of the system environment variable, to compile and run Python in the command line.
The latest version of Django is version 0.96. the compressed package can be downloaded from djangoproject.com on the official site. Decompress the package and enter the Django Directory. execute python setup in the command line. py install, so that Django will be installed in the site-packages directory of Python as a third-party module, and then add the bin directory path in Django to the environment variable path, in this way, various commands provided by Django can be conveniently used in the command line.
Start Django journey
In the following steps, we will use the Django framework to implement a complete and small Web application. An application instance creates a news announcement board. you can add news categories and entries from the background, and then display news statistics on the front-end page. In the application implementation process, we will gradually introduce the Django development method and its quick experience.
To help developers implement different functions, Django provides many development commands. most of the tedious operations are implemented by Django integrated in simple command line prompts. Now open the command prompt, enter the directory where you want to create the application, type the django-admin.py startproject news command, call the Django console command to create a new project named news, at the same time, Django also generates the following four files with different division of labor under the newly created news folder.
1. _ init _. py
File _ init _. py indicates to the Python compiler that the content in the current folder is the Python project module.
2. manage. py
Manage. py is a Python script file that works with the Django command line tool django-admin.py to manage the configuration of the created Project.
3. settings. py
This is the configuration file of the Django Project. the project-related project module and global database configuration information are all set in settings. py.
4. urls. py
The URL. py file is used to configure URL address ING and manage URL address formats.
After a new project is created, Django has prepared a lightweight Web server for you to test and use during development. The developer only needs to enter the project directory at the command prompt and type the command manage. py runserver, you can start the Web server to test the newly created Project. if there is no startup error, you will see the following prompt: "Development server is running at http: // 127.0.0.1: 8000/"indicates that the current project can be accessed through port 8000 of the local machine. Open the preceding address in a browser. The initial page of the Django project shown in 1 will appear in front of the reader.
Figure 1. Django project initial page
You can use Ctrl + Break or Ctrl + C in the command line to stop the Web server started by the runserver command. Of course, the built-in Django Web server is generally used only during development and testing. when the Django project is actually released, you can deploy the Django application on Apache by loading the mod_python.so module, to facilitate Web access management and configuration.
Django model definition
After the project is created, you can compile the Django application module. Type the python manage command. py startapp article. the command will generate a module named article in the current project, except for the _ init _ that identifies the Python module __. py file, there are two additional files models. py and views. py.
In traditional Web development, a large part of the workload is consumed in creating data tables and setting table fields in the database. Django provides a lightweight solution for this purpose. With the object relationship ing mechanism in Django, you can use the Python language to perform operations on entities in database tables. the description of the object model needs to be configured in the models. py file.
In the current project, two Models are required, which correspond to the List table and Item table respectively, to store news classification and news entries, each Item has a foreign key to mark the document category. Next, open the models. py file created by Django, add the location of the module 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 classification. the definitions in the above model are converted by Django into a structured query language that directly interacts with the database to create a data table, create a table named List. the two fields in the table are the automatically generated integer primary key id of Django and the VARCHAR type field title with a maximum width of 250 characters, the uniqueness constraint is defined in the title field to ensure that the news category does not have the same name.
In the List file, the function _ str _ () is also defined to return the title field represented by the self string. In Meta, the sorting method of List tables in alphabetical order of titles is set. In Admin-like settings, Django is allowed to automatically generate the Django superuser background management portal for the current Models model. the keyword pass setting Django will generate the background management interface by default. This part can be seen in later chapters, and we can also appreciate the unique charm of Django. Next, we will add the Models model corresponding to the news Item, as shown in the code below:
List 2. add a 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 corresponding to the Item data table is a little complicated, but not obscure. The code first introduces the datetime type, which is used to define the created_date field indicating the document creation date, and uses the standard function datetime. datetime. now of Python to return the current date of the system to set the default value of the field. In the ordering setting of record sorting, the "-" symbol is arranged in descending order of the date. if the document creation date is the same, it is sorted in alphabetical order of the title.
So far, the two data tables to be defined in the model section of the application have been created. The next step is to deploy Django and generate the Models model that has been written in the database.
Deployment of Django module
In Django, settings related to the project global must be added in the configuration file settings. py. I use MySQL as the background database and have created a database named django_news in MySQL. You need to set DATABASE_ENGINE = "mysql" and DATABASE_NAME = "django_news" in the corresponding location in the settings. py file ".
Note that if you use the SQLite database, Django can automatically create a new database in SQLite based on the database name, while in MySQL, PostgreSQL, or other databases, you must first create a database with the specified name. When using a MySQL database, you need to install an additional Python link Library MySQLdb-1.2.1 for MySQL, which can be found at the site.
The following two items are DATABASE_USER and DATABASE_PASSWORD. you need to enter the user name and password for accessing the database based on the local settings. If the database is installed on another machine or the listening port of the database is changed, you must set the DATABASE_HOST address and DATABASE_PORT. The Mysql database used by the author is set:
DATABASE_USER = 'django' DATABASE_PASSWORD = 'django_password'
To enable Django to identify the application modules added by developers, you need to define the list of applications loaded by the Django project in the INSTALLED_APPS section of the settings. py file. By default, some built-in modules required for running the Django project have been added to the list. we also need to compile the application module news. add article Le and add Django that comes with django. contrib. admin application module. the modified code is as follows:
Listing 3. add required modules
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.admin', 'news.article', )
After the admin module is added, you cannot use the admin background management interface of Django immediately. you need to open urls under the root directory of the News project. in the py file, remove the # comment after "# Uncomment this for admin:", so that Django redirects the URL for the management interface to "(r' ^ admin/', include ('Django. contrib. admin. urls '), "available, so that upon access to the admin module, Django can smoothly parse the access address and switch to the background management interface.
After the configuration file is changed, run the manage. py syncdb command at the command prompt of the News project. Django automatically maps the ORM database based on the definition of the model, blocking the preparation of the underlying database details and SQL queries.
The time has come to show the charm of Django. the Django framework will give developers a magical experience. With the rolling prompt after command execution, Django has automatically created corresponding tables and fields in the database based on the modeling file we just defined in models. When executing the command, you will be prompted to create a "superuser" account to log on to the background management page automatically created by Django to manage the model. Command Prompt 2 for synchronously updating database tables during command execution is shown below:
Figure 2. synchronously update the database table during Django command execution
The best way to maintain learning motivation is to find a little sense of accomplishment at any time. let's take a look at the work completed by these steps. Run manage again. py runserver to start the built-in Django Web server, access the address http: // 127.0.0.1: 8000/admin/in the browser, and log on with the account and password of the superuser user you just created, 3. the beautiful Django background management interface is displayed.
Figure 3. Django background management interface automatically generated based on model
In the admin management interface, the models modules defined in the application are displayed. when you click view, the list of database objects in models is displayed. The background management interface provided by Django allows you to directly change or Add database fields. Next, click "Add" next to "Lists" to Add a new news category. In the title field, type "Sports News" or another category you like and save it. Click "Add" in the "Items" Item, and fill in the first Item of the news. each Item corresponds to a category Item in the List, as shown in interface 4 for adding Items, because association between tables is set, the Django Item management interface automatically generates content for the added List category drop-down option.
Figure 4. page for adding news entries
The convenient backend management interface of Django saves a lot of time for Web developers. Currently, only the default backend 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 the control layer and performance layer of Django
At this point, the model layer in the Django project has been processed. The following is how to use code to interact with the fields defined in models. this is the View part of Django. 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:
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 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:
Listing 5. news_report template code
News statistics list News statistics list {% for list_dict in article_listing %}
- News classification: {list_dict.items_title }}
- News count: {list_dict.item_count }}
- Number of published news: {list_dict.items_complete} ({list_dict.percent_complete }}%)
{% Endfor %}
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:
The code is as follows:
Icle/templates ',
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:
The code is as follows:
(R '^ report/$', 'news. article. views. news_report '),
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.
Conclusion
The emergence of the Django development framework makes all the work in this example concise, orderly, and 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 grown from a potential competitor of ROR to a Python framework that can rival it. If we talk about the gap with the Ruby framework ROR, perhaps the most lacking of Django is the huge user group of ROR.
After reading this article, readers are planning to step into the wonderful world of Django. they can read more development documents on the Django official site www.djangoproject.com and subscribe to the Django email discussion Group on Google Group, or follow Django's official Tutorial Guide to start a journey that allows your thoughts to soar. I believe that what you get in this process is not just a novel experience of Django development.
I hope more readers will use the Django framework and more people will pay attention to the development of Django and even participate in Django project development, contribute to the open-source community. We look forward to the rapid development of Django and the brilliant future of the Rails framework implemented by Python!