Learn more about the use of the Django Open source framework

Source: Internet
Author: User
Tags install django
There are many different Web frameworks under Python. Django is one of the most iconic players in the heavyweight class. Many successful websites and apps are based on Django. Django is an open-source Web application framework written by Python. Let's take a step at a pace.

This article is for beginners who have a python base and are just touching the web framework.

Environment: Windows7 python3.5.1 pycharm Pro Django version 1.10 pip3

First, Django Introduction

Baidu Encyclopedia: Open source Web application framework, written in Python language ...

Focus: A chatty frame, everything for you to think about.

1. Introduction to the Web framework

Before you introduce Django, you must first introduce concepts such as Web frameworks.

Web framework: Someone else has set up a Web site template, you learn its rules, and then "fill in the blanks" or "modify" the way you want.

The architecture of the general web framework is this:

Other Python-based web frameworks, such as tornado, flask, and webpy, are cut and deleted within this range. For example, Tornado uses its own asynchronous non-blocking "Wsgi", flask only provides the most streamlined and basic framework. Django uses WSGI directly and implements most of the functionality.

2. MVC/MTV Introduction

MVC Baidu Encyclopedia: Full Name Model View controller, which is the abbreviation of models-View-controller, a kind of software design model, organizes the code with a method of business logic, data, interface display separation. Aggregating business logic into a single component does not require rewriting business logic while improving and personalizing the interface and user interaction.

Popular explanation: A form of file organization and management! Don't be intimidated by abbreviations, this is a way to put different types of files in different directories, and then take a tall name. Of course, it brings a lot of benefits, such as front-end separation, loose coupling and so on, it is not explained in detail.

Model: Define database-related content, typically in a models.py file.

View: Defines static Web page files such as HTML, that is, HTML, CSS, JS and other front-end things.

Controller: Define business logic related, which is your main code.

MTV: Some Web frameworks think that MVC's literal meaning is awkward, just change it for a bit. View is no longer HTML related, but the main business logic, equivalent to the controller. HTML is placed in templates, called a template, so MVC becomes MTV. This is actually a word game, and MVC is essentially the same, changed a name and called, the new.

The 3.Django MTV model organization

Directories, there must be a mechanism for them to be coupled inside. In Django, URLs, ORM, static, settings, and so on, play an important role. A typical business process is as follows:

So what do we learn from Django?

1. Directory Structure specification

2. How URLs are routed

3. Settings configuration

4.ORM operation

5. Template rendering

6. Other

Ii. Examples of Django projects

1. Program Installation

python3.5, PIP3 and Pycharm Professional editions are installed on their own.

(1) Installing Django:

This is only a simple way to install the PIP3 command.

Win+r, call up cmd, Run command: PIP3 install Django, automatically installs the latest version provided by PyPI.

After the installation is complete as shown:

(2) Configuring the system environment

After a successful installation of Django, the path in the Django-admin.exe file is found and added to the operating system environment variable. This will be more convenient for subsequent calls.

Run: Django-admin help, can see the following content indicates OK.

2. Create a Django Project

Under the command-line interface like Linux, you can use the commands and vim provided by Django to develop your project. However, it is recommended to use Pycharm, the best python development IDE in the present

, it is powerful and user friendly. (All of the following operations are performed in Pycharm.) )

Click: File-->new Project, the following dialog box appears.

Select the Django column and enter the project name, which uses the MySite of international practice. Select the Python interpreter version and click Create.

Django will automatically generate the following directory structure:

The directory with the same name as the project is a configuration file, and the templates directory is the HTML file that is the T in MTV. Manage.py is a Django project management file.

3. Create an App

You can include multiple apps in each Django project, like sub-systems, sub-modules, features, and so on, in a large project, independent of each other, but also associated.

All apps share project resources.

Enter the command in the terminal terminal below Pycharm:

Python manage.py Startapp CMDB

This creates a app,django, called the CMDB, that automatically generates a "CMDB" folder.

4. Writing a route

The route is in the URLs file, which maps the URL entered by the browser to the appropriate business processing logic.

Simple ways to write URLs such as:

5. Writing Business processing logic

The business processing logic is in the views.py file.

With the above two steps, we point the index URL to the index () function in views, which receives the user request and returns a "Hello World" string.

6. Run the Web service

Now we are ready to run the Web service.

The command line is in the following way: Python manage.py runserver 127.0.0.1:8000

But in Pycharm, you can do this:

In the Upper toolbar, locate the icon shown below.

Click the drop-down arrow

Click Edit Configurations

Fill in Host: 127.0.0.1 Port: 8000

After OK, click on the green triangle and the Web service will run.

Automatically jump to the browser program interface as shown in the figure. Yes, it is. 404 Pages:

Modify the URL, add "/index", everything OK!

At this point, one of the simplest Django-authored Web services started successfully.

7. Return HTML file

What do we return to the user's browser above? A string! In fact, this is certainly not possible, usually we are returning the HTML file to the user.

Below, we write such a index.html file:

Then modify the views file:

In order for Django to know where our HTML files are, we need to modify the corresponding contents of the settings file. But by default, it just works, and you don't have to modify it.

Next, we can restart the Web service. In the browser refresh, you will see the style of "Hello World".

Note: Here is a small trick, in many times to restart the service frequently, because the port is not released because of the reason, easy to start the service, modify the port is OK.

8. Using static files

We can already return the HTML file to the user, but not enough, the front-end three chunks, HTML, CSS, JS and a variety of plug-ins, they are complete is a full

The page. In Django, static files are generally placed in the static directory. Next, create a new static directory in the MySite.

Your css,js and various plugins can be placed in this directory.

In order for Django to find this directory, settings still needs to be configured:

Similarly, in the index.html file, you can introduce a JS file:

Restart the Web service, refresh the browser, and view the results.

9. Receiving the data sent by the user

Above, we return a full-featured HTML file to the user's browser. This is not enough, however, because there is no dynamic interaction between the Web server and the user.

Below we design a form, let the user enter user name and password, submit to index this URL, the server will receive this data.

Modify the index.html file first

Then modify the views.py file

At this point, when restarting the Web service, an error occurs because Django has a cross-site request protection mechanism, and we close it in the settings file.

Once again, go to the browser and refresh the page:

Input something, and then we can see the corresponding data in the Pycharm.

10. Return to the dynamic page

We received the user's data, but the return to the user is still a static page, usually we will be based on the user's data, processed and returned to the user.

At this point, Django uses its own template language, similar to JINJA2, to replace the corresponding portions of the HTML with the data provided, and to learn more about the syntax.

First transform the views.py file:

Re-transforming the index.html file:

Restart the service and refresh the browser:

As you can see, we get the data that the user has entered in real time, and it's a good interactive process to show it in real time on the user's page.

11. Using the Database

Process comes here, the Django MTV framework has surfaced, leaving only the last database part.

Above, although we interact with the user very well, but did not save any data, the page once closed, or the server restarts, everything will go back to the original state.

Without a doubt, Django operates the database with its own ORM framework and comes with its own lightweight sqlite3 database. Let's take a look at the following:

First, register the app:

Without registering it, your database will not know which app to create the table for.

Then we configure database-related parameters in settings, and if you use SQLite with your own, you don't need to modify it.

Then edit the models.py file, the M in MTV.

Here we create 2 fields, each saving the user's name and password.

The next step is to create a table of the database in Pycharm's teminal by command. There are 2 commands, namely:

Python manage.py makemigrations

Re-enter command: Python manage.py migrate

Modify the business logic in views.py

After the Web service is restarted, the browser page is refreshed, and then the data that interacts with the user can be saved to the database. Data can be read from the database at any time and displayed on the page.

At this point, a complete element, the main framework to show a clear Django project completed, is actually very simple is not it?

Iii. Summary of Django

As Python must be the web framework of Django, it's powerful, comprehensive content, but also means that there are a lot of restrictions, flexibility and poor modification, this is the fish and bear cake can not be combined. We learn Django, in fact, is to learn a software, to understand its basic principles, grasp its overall framework, keep in mind some basic rules, the rest is to keep in-depth details, and then make perfect, experience how much of the problem, there is no more advanced technology can not be mastered.

Suggestions on learning methods: Learn anything, not directly into the details, you should first understand its peripheral knowledge, look at its overall structure, and then learn its basic content, then the deep learning, polishing skills!

The full text, there is no place to ask correct, feel good, just like to support a bit.

"Recommended"

1. Special recommendation : "PHP Programmer Toolkit" V0.1 version download

2. Python Free video tutorial

3. Python's application in Data Science video tutorial

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.