How does Django work?

Source: Internet
Author: User

If you look at the article I wrote about Django , you'll find that each one is actionable, starting with the creation of the project, although there are some points to be explained in the middle. This is also a feature of my blog post, and I hope that when you see me this article is operable, whether or not have the relevant foundation.

If this is your first time contact Django , it is recommended to refer to my Django the contents of this exercise:

Http://www.cnblogs.com/fnng/category/581256.html

This article describes how Django works. If you make this process clear, then you're Getting Started with Django.

a flowchart tells you theDjango process :

URL Composition

as a website user, we first enter in the input box of the browser : http://127.0.0.1:8000/index/

The URL address consists of the following parts:

protocol type : HTTP, FTP

The HTTP protocol (hypertext Transfer Protocol, Hypertext Transfer Protocol) is the transfer protocol used to transfer the text from the WWW server to the local browser. It can make the browser more efficient and reduce the network transmission. It not only ensures that the computer transmits hypertext documents correctly and quickly, but also determines which part of the document is being transmitted, and which content is displayed first.

HTTPS (full name: Hyper Text Transfer Protocol over secure Socket Layer) is security-targeted HTTP channel, simply speaking is the security version of HTTP.

host address : Itest.info, 127.0.0.1

The former is a web address, the URL through the domain name resolution server will find the corresponding IP address. The latter is an IP address.

The 127.0.0.1 point is the IP address of the machine.

Port number : 8000

The port number is used to differentiate between different applications that identify the same host. There are many applications on one host, if you specify 8000 when you visit my host, then you will know that you are visiting the blog I developed with Django. Of course, this port can be arbitrarily allocated.

path :/index/,/admin

Typically used to represent a directory or file address on a host.

configuration of URLs

  Django handles the point of front-end requests well through the urls.py configuration file, which uses regular expressions using Python to make the match more flexible.

Open the urls.py file under Django:

 from django.conf.urls Import patterns, include, url  from  = Patterns (' ',    url (r'^admin/', include ( admin.site.urls),    URL (r'^index/$" ) Blog.views.index'),)

R ' ^index/$ '

This is a regular expression that uses Python.

Strings preceded by "R" are escaped when a similar "\ T" character appears in a string.

After the Django gets the URL address, the folder path (/index/) after the port number is configured, and the result ^index/$ can match the file path. Then it will point to the Blog.views.index address.

Blog is a folder , Views is a. py file,index is the function name.

model Models

Django uses the model to execute SQL code in the background and describe the results in Python data structures. Django also uses models to present high-level concepts that SQL cannot handle.

The model is used for database creation, to configure the database connection in the settings.py file, such as the configuration of a MySQL database:

... DATABASES= {    'default': {        'ENGINE':'Django.db.backends.mysql',        'HOST':'127.0.0.1',        'PORT':'3306',        'NAME':'MyWeb',        'USER':'User',        'PASSWORD':'123456',    }} ...

configuration information is driven from top to bottom by the drive (engine), host address (hostname), port number (port), database (name), login username (user), login password (PASSWORD).

Create the model in the application's models.py file to avoid direct manipulation of the database by creating a model to generate the corresponding database table.

 from Import Models # Create your models here. class Blogspost (models. Model):    = models. Charfield (max_length = $)    = models. TextField ()    = models. Datetimefield ()

Performing a database synchronization creates a plogspost table with the title, body, and timestamp three fields respectively. Where title is defined as a char type, defines a maximum of 150 characters, the body is the text literal type; timestamp is a datetime type.

We don't have to shut down how to create a table, just create a good model, the rest of the Djnago to help us generate the corresponding table. Here is the command to create the model as a database table:

d:\pydj\myweb>python manage.py makemigrations blogfor'blog':  0001_initial.py:- Create model Blogspostd:\pydj\myweb>python manage.py syncdb Operations to perform:  Apply all migrations:admin, blog, contenttypes, auth, sessionsrunning migrations:  Applying blog.0001_initial ... OK

The first is to perform the migration of the model under an application (blog) through Makemigrations, and then, through SYNCDB, to detect all the models under the project and find that the model has changed or that no tables have been generated, the corresponding tables will be regenerated. (versions prior to DJNAOG 1.7 only need to syncdb one command to complete the synchronization)

views View

Views can be thought of as the front-end and database man-in-the- middle, and he will read the data from the database to the front end. He also writes the data that the user wants to save to the database.

views.py

#Coding=utf-8 fromDjango.shortcutsImportRender fromBlog.modelsImportBlogspost fromDjango.shortcutsImportRender_to_response#Create your views here.defIndex (Request): Blog_list=BlogsPost.objects.all ()returnRender_to_response ('index.html',{'blog_list': Blog_list})

Here the index function does two things:

Blog_list =blogspost.objects.all ()

Query all the data in the Blogspost database and assign to the blog_list variable.

Return Render_to_response (' index.html ', {' blog_list ': blog_list})

Returns a index.html page to the browser via Render_to_response (), and returns the value of the blog_list variable to index.html.

Templates Templates

The template is the page we are familiar with, and Django comes with a template system. Its main function is how to display data, such as a view that returns a bunch of data. Are all loops displayed? And by judging only what you think is useful? Of course, in order to make the page more beautiful need to use front-end technology, such as CSS, JavaScript and so on.

Then we see the index.html page on the browser:

MTV development model

Understanding the parts of Django, let's delve into the Django development model.

  MTV Development Model

Before delving into more code, let's take some time to consider the overall design of the Django data-driven WEB application. As we mentioned in the previous section, Django's design encourages loose coupling and strict segmentation of different parts of the application. If you follow this idea, it's easier to modify one part of the application without affecting the rest. In the view function, we have discussed the importance of separating the business logic from the presentation logic through the templating system. In the database layer, we also apply the same concept to the data access logic. The concept of combining data access logic, business logic, and presentation logic is sometimes referred to as the Model-view-controller (MVC) pattern of the software architecture. In this model, the model represents the data access layer, and View represents the part of the system that chooses what to display and how it is displayed, and Controller refers to the part of the system that accesses the model based on user input and as needed to determine which view to use.

Why use abbreviations?

Clearly defined patterns like MVC are primarily used to improve communication between developers. Instead of telling colleagues, "Let's use abstract data access, then separate a layer to display the data, and add a layer to control it in the middle", a generic statement will make you profit, you just need to say: "We use the MVC pattern here." ”。 Django adheres closely to this MVC pattern, which can be called an MVC framework. The following are the meanings of M, V, and C in Django:

    • M, the Data Access section, which is handled by the Django database layer, and what this chapter will tell you.
    • V, select the section that shows what data to display and how to display it, handled by the view and template.
    • C, depending on the part of the user's input delegation view, the Django framework invokes the appropriate Python function for the given URL, based on the URLconf setting.

Since C is handled by the framework itself, and Django is more concerned with models, templates, and views, Django is also known as the MTV framework. In the MTV development model:

    • M represents the model, which is the data access layer. This layer handles all data-related transactions: How to access, how to verify the validity
    • T stands for template, which is the presentation layer. This layer handles performance-related decisions: How to display in a page or other type of document.
    • V represents the view, which is the business logic layer. This layer contains the relevant logic for accessing the model and tuning the appropriate template. You can think of it as a bridge between the model and the template.

If you're familiar with other MVC web development frameworks, such as Ruby on Rails, you might think that the Django view is a controller, and the Django template is a view. Unfortunately, this is the wrong understanding of the different interpretations of MVC. In Django's interpretation of MVC, views are used to describe the data to be presented to the user, not how the data is presented and what data is presented. In contrast, Ruby on Rails and some similar frameworks advocate that the controller is responsible for determining what data is presented to the user, and the view only determines how the data is presented, not what data is presented.

None of the two interpretations is more correct. It is important to understand the underlying concepts.

How does Django work?

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.