Quick start of the Django framework

Source: Internet
Author: User
Tags auth time zones sessions sqlite sqlite database django website install django pip install django
1. What's Django?

Django is an advanced Python WEB framework that was originally designed by the Lawrence Publishing Group in Canada to manage the content of its news sites. It encourages rapid development and cleanliness and is responsible for many of the hassles of Web development, so developers can focus on writing applications without having to reinvent the wheel. Django was released under the BSD license in July 2005.
The following benefits may allow you to consider the Django framework: Django is free and open source; Django is a comprehensive web framework called the perfectionist, can build better Web applications faster, and reduce code; Django's aim is to help developers quickly move from concept to completion Django's MVC design is beautiful, Django provides fast, flexible scalability, can use the original SQL statements in Django, and Django brings a management interface ...

Django is a all-inclusive Web framework, but it takes a bit of learning time to customize it.
More introduction: https://www.djangoproject.com/ 2. MVC and MVT

MVC is a typical web development design pattern, MVC is the abbreviation of Model-view-controller, which : model, Modeling: it refers to the relationship between object resources map to the database table, mainly encapsulates access to the database layer, Curd the data in the database; view, view: It refers to the appearance of the Web page we see, but also need to use a page template, to encapsulate the results, generate HTML page; Controller, controller: The function that each page needs to implement, implemented by functions corresponding to the path of the Web page, which is the controller that receives requests, processes business logic, consolidates models (databases), and Views (Web pages).

However, Django's MVC differs from traditional MVC in that it belongs to the MVT architecture, where: m represents Model: The same as the M function in MVC, which is responsible for interacting with the database and processing data; V for View: with MVC is responsible for receiving requests, fetching data, returning results, and T representing Template: the same as the V feature in MVC, which encapsulates the HTML page that is to be returned.

Note: Processing HTTP request responses between client and server requires implementation of the WSGI protocol.

The Python Web server gateway Interface (Python Web servers gateways Interface, abbreviated as WSGI) is an interface between Python applications or frameworks and WEB servers that has been widely accepted and basically achieves portability goals. 3. Install Django

Open the download page of the Django website with detailed installation methods. We should be aware of the version of the choice, the following is the official version of the release plan:

The development environment can use newer versions, but the production environment recommends the use of the LTS version.
My lab environment is a 64-bit Ubuntu 16.04,python version of 3.5.2,PIP version 9.0.3, ready to install a Django version of 1.11.11. The installation process is as follows:
To install using PIP online:

$ pip Install django==1.11.11

This installation will be installed in the default directory of Python, and we can view it with PIP show:

$ pip show Django
name:django
version:1.11.11
summary:a High-level Python WEB framework that encourages rap ID development and clean, pragmatic.
home-page:https://www.djangoproject.com/
Author:django Software Foundation
author-email: foundation@djangoproject.com
License:bsd
Location:/usr/local/lib/python3.5/dist-packages
Requires: Pytz

You can also download the installation package first, and then specify the directory installation:

$ pip Download django=1.11.11-d./
$ pip Install DJANGO-1.11.11-PY2.PY3-NONE-ANY.WHL

Check to make sure the installation is successful:

$ pip Freeze
$ python3-m Django--version
4. Project creation and Operation 4.1 Creating a project

If you are using Django for the first time, then go to your working directory and execute the following command, which will automatically generate some code to build the Django project.

$ django-admin Startproject MyWeb

Go to the MyWeb directory and see what Startproject created:

$ tree
.
├──manage.py
└──myweb
    ├──__init__.py
    ├──settings.py
    ├──urls.py
    └──wsgi.py

These directories and files function as follows: The external myweb/root is just a container for a project. Its name has nothing to do with Django; You can rename it to anything you like. manage.py: A command-line utility that allows you to interact with this Django project in a variety of ways. You can read all the details manage.py in Django management and manage.py. The internal myweb/directory is the actual Python package for your project. Its name is the Python package name (for example, myweb.urls) that you need to import any of the content. myweb/__init__.py: An empty file that tells Python this directory should be considered a python package. myweb/settings.py: Setup/configuration for this Django project. The Django settings will tell you all about how the settings work. myweb/urls.py: URL declaration for the Django project; The "directory" of your Django power Web site. MYWEB/WSGI.PY:WSGI a compatible WEB server provides a service entry point for your project. 4.2 Running the development server

In the external myweb/directory, execute the following command:

$ Python3 manage.py Runserver

At this point, our Django development server is running, but the following warning may appear:

You have unapplied migrations; Your app May is not work properly until they are.
Run ' python manage.py migrate ' to apply them.

This is because the server defaults to the SQLite database, and we do not currently have a database or are not properly configured to temporarily ignore it.
Then open the browser, enter Http://127.0.0.1:8000/, and see the following page stating that our Django development server is running.

By default, the Runserver command starts the development server on the internal IP of Port 8000. If you want to specify a port-open service, such as port 8080, you can do this:

$ python3 manage.py runserver 8080

Of course, we can also specify IP, such as my experimental environment IP is 192.168.66.169, you can do this:

$ python3 manage.py runserver 192.168.66.169:8080

Or is:

$ python3 manage.py runserver 0:8,080

Note: 0 is a 0.0.0.0, is a special IP address, representing all the IP address of the machine, regardless of how many network ports, how many IP, listening to the local 0.0.0.0 on the 8080-port is equal to monitor all IP on the machine 8080 ports.
But this time, we enter http://192.168.66.169:8000/in the browser, we may see the following page:

This is because the Django development server can only be accessed locally by default, and all we have to do is configure the allowed_hosts in the next myweb/settings.py, for example:

allowed_hosts = [' 192.168.66.169 ', ' localhost ', ' 127.0.0.1 ']

Or simply like this, to support all:

allowed_hosts = [' * ']

Note: The launch here is a lightweight Web server written purely in Python, combined with Django, so developers can develop quickly without having to process configuration production servers (such as Apache) until you are ready to produce. 5. Application creation and use 5.1 to create an application

Django brings a utility that automatically generates the basic directory structure of your application, so you can focus on writing code instead of creating a directory. In the external myweb/directory, execute the following command:

$ python3 manage.py Startapp MyApp

We found one more myapp/directory, expanded as follows:

$ tree myapp/
myapp/
├──admin.py
├──apps.py
├──__init__.py
├──migrations
│   └──__init __.py
├──models.py
├──tests.py
└──views.py
5.2 Writing the first view

Open the myapp/views.py file and add the following Python code:

From django.http import HttpResponse

def index (request): Return
    to HttpResponse ("Hello, World.") ' Re at the MyApp index. Meow ")

This is the simplest view in Django, and to call the view, we need to map it to a URL. Therefore, we need a urlconf--to create a URLconf in the MyApp directory and create a file named urls.py.
Edit the myapp/urls.py file as follows:

From Django.conf.urls import URLs from
. Import views

urlpatterns = [
    url (R ' ^$ ', Views.index, name= ' index ') ),
]

Next, we will also point the root URLconf to the Myapp.urls module. Edit the list of urlpatterns in myweb/urls.py, as follows:

From Django.conf.urls import include, URLs from
django.contrib Import admin

urlpatterns = [
    url (R ' ^admin/', admin.site.urls),
    url (r ' ^myapp/', include (' Myapp.urls ')),
]

The Include () function is used here, so we need the import django.conf.urls.include, and the Include () function allows references to other urlconfs.
Note: The regular expression of the include () function does not have a $ (string matching character), but a trailing slash. Whenever Django encounters an include (), it excludes any part that matches the point and sends the remaining strings to the accompanying URLconf for further processing.
Okay, now rerun the Django Development server:

$ python3 manage.py runserver 0:8,000

Browser input http://localhost:8000/myapp/, you can see the following page:

5.3 url () function introduction

The Django URL () function can receive four parameters, two required parameters: Regex, view, and two optional parameters: Kwargs, name. Regex: Regular expression that matches the URL that performs the corresponding second argument view view: The URL request that is used to match the regular expression Kwargs: The parameter name of the dictionary type used by the view is used to reverse get URL 6. Project Model 6.1 connection MySQL Database settings

In myweb/settings.py, you have the following code:

DATABASES = {'
    default ': {
        ' ENGINE ': ' Django.db.backends.sqlite3 ', '
        NAME ': Os.path.join (Base_dir, ' Db.sqlite3 '),
    }
}

In other words, the Django default configuration uses SQLite. If you do not use SQLite as a database, you need additional settings, such as we use the MySQL database in this example, and you must add User,password and HOST configuration information.
In my local MySQL, a database named Django-test has been created in advance for testing.


The final DATABASES configuration is as follows:

DATABASES = {'
    default ': {
        ' ENGINE ': ' Django.db.backends.mysql ', '
        NAME ': ' django-test ',
        ' USER ': ' Root ',
        ' PASSWORD ': ',
        ' HOST ': ' localhost ',
        ' PORT ': ' 3306 ',
    }
}

Note: Django uses MySQL database to install Pymysql, if the small partners are not installed, you can perform the following command to install:

$ pip Install Pymysql

Then add the following code in myweb/__init__.py to import the Pymysql:

Import Pymysql
pymysql.install_as_mysqldb ()
6.2 Creating a model

Below, in the application we created earlier, create a Model class that Stu table information operations. Edit the myapp/models.py file as follows:

From django.db import Models

# Create your models here.

Class Stu (models. Model):
    ' custom stu table corresponding model class '
    #定义属性: Default primary key self-increasing ID field does not write
    id = models. Autofield (primary_key=true)
    name = models. Charfield (max_length=16) Age
    = models. Smallintegerfield ()
    sex = models. Charfield (max_length=1)
    classid=models. Charfield (max_length=8)

    # defines the default output format
    def __str__ (self): return
        "%d:%s:%d:%s:%s"% (Self.id,self.name, SELF.AGE,SELF.SEX,SELF.CLASSID)

    # Customize the corresponding table name, default table name: Myapp_stu
    class Meta:
        db_table= "Stu"
6.3 Activation Model

To activate the model, which is to include the application in our project, you need to add a reference Installed_apps to its configuration class in the settings. The Myappconfig class is in the myapp/apps.py file, so its path should be "Myapp.apps.MyappConfig".
Edit the myweb/settings.py file and add the path to the Installed_apps setting, as follows:

Installed_apps  =  [ 
    ' django.contrib.admin ',
    ' Django.contrib.auth
    ', ' Django.contrib.contenttypes ',
    ' django.contrib.sessions ', '
    django.contrib.messages ',
    ' Django.contrib.staticfiles ',
    ' myapp.apps.MyappConfig ',  #或者直接写 MyApp
]
6.4 Using Models

Here's how to get the data for the model, and before that, we've created a Stu datasheet in the Django-test database and added some of the data. As shown below:

Next we use the model in two ways.

6.4.1 into the interactive Python shell using Django API operations

Into the Python Shell interactive interface:

$ python3 manage.py Shell

A simple interaction is as follows, first import Stu, then get all the information of the model, then print out all the records, we can get a single piece of information.

python 3.5.2 (default, Nov 2017, 16:37:01) Type "copyright", "credits" or "license" for the more

Information.
IPython 2.4.1--an enhanced Interactive Python.         ?
-> Introduction and Overview of IPython ' s features.
%quickref-> Quick Reference.
Help-> the Python ' s own Help system.   Object?

-> details about ' object ', use ' object?? ' for extra details. In [1]: from myapp.models import Stu into [2]: mod = stu.objects in [3]: Lists = Mod.all () in [4]: for V in lists:.. .: Print (v) ...: 1:apple:8:female:1 2:rudy:10:male:1 3:tina:9:female:1 4:alexander:6:male:1 5:carrie:5:female: 1 6:joe:7:female:1 7:elsa:11:female:1 8:blaise:12:male:1 9:lisa:12:female:2 10:jhon:12:male:2 in [5]: Mod.get (id=1) out [5]: <Stu:1:Apple:8:female:1> in [6]: Mod.get (id=2) out[6]: <Stu:2:Rudy:10:male:1> in [7]: Mod.get (id=3) O UT[7]: <Stu:3:Tina:9:female:1> in [8]: Quit 

Note: I am installing here Ipython, which is an enhanced version of the Python Shell, so it may not be the same as your instructions. The Ubuntu installation Ipython is simple: $ sudo apt-get install Ipython.

6.4.2 is used in MyApp-applied view

Edit the myapp/views.py file, import the Stu, and implement the STU function:

From django.shortcuts import render to
django.http import HttpResponse from
myapp.models import Stu

# Create your views here.

def index (Request): Return
    HttpResponse ("Hello, World.") ' Re at the MyApp index. Meow ")
    #return render (Request," index.html ")

def Stu (Request):
    #获取所有stu表信息
    lists = Stu.objects.all ()
    print (lists)
    #获取单条学生信息
    print (Stu.objects.get (id=1)) return

    HttpResponse ("OK")

Don't forget. Also configure the access route for the Stu function in myapp/urls.py:

URL (r ' ^stu$ ', Views.stu),

Restart the Django Development server and enter Http://localhost:8000/myapp/stu in the browser. 7. Enable background management of Web sites

The Django framework has a very powerful application function-an automated management interface that is often used by web platform administrators to manage the entire web platform. 7.1 Data Migration

The first time you enable background management, you first need to migrate data. Data migration is to migrate data from Django's backend management module to myweb database, so if your myweb isn't connected to the database, go back to section 6.1.
By default, Installed_apps contains the following applications in the settings.py configuration file, which are provided by Django: Django.contrib.admin-Manage the Web site. You will soon use it. Django.contrib.auth-Certification System. Django.contrib.contenttypes-Framework for content types. Django.contrib.sessions-Session Framework Django.contrib.messages-message framework. Django.contrib.staticfiles-the framework for managing static files.

With these Django self-contained applications, we need to create some data tables in the database to correspond before we can use them. Therefore, we run the following command for data structure migration:

$ Python3 manage.py Migrate

The migrate command looks at the Installed_apps settings and creates any required database tables based on the database settings in the myweb/settings.py file and the database migration that is included with the application.
Look at MySQL, a lot of data tables:

At this time, access to http://localhost:8000/admin/, into the background login interface, AH ~ account number/password.

7.2 Creating an administrator user

Yes, we also need to create a user who can log on to the admin site (superuser). Execute the following command:

$ Python3 manage.py Createsuperuser

According to the prompts to enter the user name and password information can be. 7.3 Start the development server

By default, the Django administrator has been activated and we have restarted the development server:

$ python3 manage.py runserver 0:8,000

Login Admin background, enter the user name and password just created, login successful.

7.4 Setting time zones and Languages

But English is not very accustomed to it, switch into Chinese chant. To edit the myweb/settings.py configuration file:

Language_code = ' Zh-hans '
time_zone = ' Asia/shanghai '

Refresh, see Chinese ~

7.5 Adding custom applications to background management

However, where are our custom applications. Does not appear on the Background Management index page. To do this, open the myapp/admin.py file and edit the code as follows:

From django.contrib import admin from
myapp.models import Stu

admin.site.register (STU)

Refresh:

7.6 More in-depth design background management

Edit the myapp/models.py file and add the following information in the Stu class to allow background management to display the text segment:

Class Stu (models. Model):
    ' custom stu table corresponding model class '
    #定义属性: Default primary key self-increasing ID field does not write
    id = models. Autofield ("School Number", primary_key=true)
    name = models. Charfield ("name", max_length=16) Age
    = models. Smallintegerfield ("age")
    sex = models. Charfield ("Gender", max_length=1)
    classid=models. Charfield ("Class", max_length=8)

    # define the default output format
    def __str__ (self): return
        "%d:%s:%d:%s:%s"% (Self.id, SELF.NAME,SELF.AGE,SELF.SEX,SELF.CLASSID)

    # Customize the corresponding table name, default table name: Myapp_stu
    class Meta:
        db_table= "Stu"
        verbose_name = ' Browse student information '  
        verbose_name_plural = ' Student Information management '

Edit myapp/admin.py files to achieve personalized customization of information management:

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.