Python's Web application framework--django

Source: Internet
Author: User

A: Introduction

Python has a lot of web frameworks, and individuals have looked up, including Django, pylons, Tornado, bottle, and flask, among which the largest number of users is Django, And I learned Django because the Django framework was used in OpenStack.

Django is an open-source Web application framework, written in Python, using MVC's software design pattern, model M, view V, and controller C.

Two: Installation

Since Django2.0 will no longer support python2.x, be sure to pay attention when installing.

2.1.python3.x+django2.x

Install python-setuptools

Yum Install Python-setuptools

Download the Django installation package

Easy_install Django
2.2.python2.x+django1.x

Install python-setuptools

Yum Install Python-setuptools

Download the Django installation package

Download Source Bundle: https://www.djangoproject.com/download/

Click Download version 1.11 in the history version.

Enter the following command and install:

Tar xzvf django-x.y.tar.gz    # unzip the download package CD django-x.y                 # Go to the Django directory python setup.py install       # Execute the Install command /c5>
2.3 Inspection
[Email protected] django]# Pythonpython 2.7.3 (default, May, 14:49:08) [GCC 4.8.0] on Linux2type ' help ', "Copyright", "credits" or "license" for more information.>>> import django>>> Django. VERSION (1, 6, 5, ' final ', 0) >>>     
Three: Create the first project 3.1 Create and browser show

Here you will learn to use the django-admin.py management tool to create.

Create a project

django-admin.py  startproject  Helloword

Enter project to view directory structure

[[Email protected] ~]# CD helloworld/[[email protected] helloworld]# Tree.├──helloworld          container for--------project │├──__in it__.py     --------An empty file that tells Python that the directory is a python package     │├──settings.py--------The settings, configuration │├──urls.py of the Djiango project         --- -----The URL statement for the Djiango project, a Djiango-driven Web site "directory" │└──wsgi.py         --------a portal to a WSGI-compatible Web server to run your project. └──manage.py           --------A very useful management tool that enables various interactions with Django 1 directory, 5  

Start the server

Python manage.py runserver 0.0.0.0:8000

Then enter the server in the browser ip:8000

Be aware of this:

1: Turn off the firewall,

2: If "Dango error:DisallowedHost:Invalid http_host Header:" appears. You can need to the add U ' to allowed_host ' error, just modify the settings.py file

allowed_hosts = [' * '] # Here The requested host has been added *

3.2 Modifying the contents of a view

1. Create a new file view.py file in the Helloworld/helloworld directory and enter the code:

From django.http import httpresponse def hello (request):    return HttpResponse ("Hello World!")

2. Comment The original code in the urls.py file and add the following code

From django.conf.urls import urlfrom . Import viewurlpatterns = [    url (r ' ^$ ', View.hello),] 

Then start Django and visit the browser to see the following content

3.3 Modifying URLs

Modify the urls.py code to add the following red similar characters

From django.conf.urls import urlfrom . Import viewurlpatterns = [    url (r ' ^yaohong$ ', View.hello),]
         

Then start the Django service

Re-enter the original server ip:8000 will appear the following error

Because you need to add the characters you just added after the port number, as shown in

Four: Template 4.1 Implementation template data separation 1. Create a template file

Create the Templates folder under HelloWorld and create it under the folder hello.html,helloworld/templates/hello.html

[Email protected] helloworld]# TREE.├──DB.SQLITE3├──HELLOWORLD│├──__INIT__.PY│├──__INIT__.PYC│├──SETTINGS.P Y│├──settings.pyc│├──urls.py│├──urls.pyc│├──view.py│├──view.pyc│├──wsgi.py│└──wsgi.pyc├──mana Ge.py└──templates    └──hello.html2 directories, files

Add the following code in the hello.html

2. Configure the template path in settings.py

Modify the DIRS in TEMPLATES to [base_dir+ "/templates",],

TEMPLATES = [    {        ' backend ': ' Django.template.backends.django.DjangoTemplates ',        ' DIRS ': [],        ' DIRS ': [base_dir+ "/templates",],        ' App_dirs ': True,        ' OPTIONS ': {' context_processors ' : [' Django.template.context_processors.debug ', ' django.template.context_processors.request ', ' Django.contrib.auth.context_processors.auth ', ' django.contrib.messages.context_processors.messages ',] , }, },]

3. In view.py, you want the template to submit data

Add the following code to the view.py, where "Hello" is the variable in the template, "Hello word! My name is Yaohong "for the submitted data

From django.shortcuts import renderdef Hello (Request):    Context          = {}    context[' hello '] = ' Hello ' world! My name is Yaohong '    return render (Request, ' hello.html ', context) 

4. Start the server
Python manage.py runserver 0.0.0.0:8000

Enter the address in the browser

4.2Django Template Label

If/else Label

{% if condition1%}   ... display 1{% elif condition2%}   ... display 2{% Else%}   ... di Splay 3{% endif%}     

For label

{% for athlete in athlete_list%}        {% to sport in Athlete.sports_played%}        <li>{{Sport}}</li>    {% endfor%}    </ul>{% ENDfor%}     

Ifequal/ifnotequal Label

The {% ifequal%} label compares two values and displays all values in {% ifequal%} and {% endifequal%} when they are equal.

{% ifequal user CurrentUser%}    {% endifequal%} 

Comment Label

{# This is a comment #}

Filter filters

#{{name}} variable is processed by the filter lower, the document capitalization conversion text is lowercase {{name|lower}}
#将第一个元素并将其转化为大写.
{{ my_list|  First|}}    

Include tags

{% include "nav.html"%}

Template inheritance

Start by creating a new file to be inherited, named base.html

<! DOCTYPE html>    {% block mainbody%}       <p>original</p>    {% Endblock%}</ body>   

Inherit the base.html page again in hello.html

{% extends "base.html"%}{% block mainbody%}<p> inherited base.html file </p> {% Endblock%}  

V: Model 5.1 install MySQL

First check to see if the system is self-bringing or we have installed MySQL,

Rpm-qa | grep MySQL

Install and start MySQL:

#非centos7版本
Yum Install Mysqlyum install mysql-serveryum install mysql-devel
Service mysqld Start

#centos7版本执行如下
Yum Install Mariadb-server mariadb

Systemctl start mariadb  #启动MariaDB#设置开机启动

Verifying the installation

Execute the following statement to see the version information, if there is no output, that the MySQL is not installed successfully

Mysqladmin--version

Set up users

Change root password

mysqladmin-u root password "new_password";

Set test user password

Mysql-u Root-p>grant all privileges on test.* to ' test ' @ ' localhost '     identified by ' test123 ';> GRANT all privileges the test.* to ' test ' @ ' percent '     identified by ' test123 ';   

5.2 Modifying the corresponding configuration 1. Database configuration

Under helloworld/helloworld/settings.py, modify databases{} as follows:

DATABASES = {'    default ': {        ' ENGINE ': ' Django.db.backends.mysql ',         ' NAME ': ' Test ',        ' USER ': ' Test ', '        PASSWORD ': ' test123 ', ' HOST ': ' localhost ',' PORT ': ' 3306 ',}}  

2. Defining the Model

Create an App

Go to HelloWorld folder

django-admin.py Startapp Testmodel

After the creation is complete, the directory is as follows:

[Email protected] helloworld]# TREE.├──DB.SQLITE3├──HELLOWORLD│├──__INIT__.PY│├──__INIT__.PYC│├──SETTINGS.P   Y│├──settings.pyc│├──testdb.py│├──testdb.pyc│├──urls.py│├──urls.pyc│├──view.py│├──view.pyc│ ├──wsgi.py│└──wsgi.pyc├──manage.py├──templates│├──base. Html│└──hello.html└──testmodel    ├──admin.py    ├──admin.pyc    ├──apps.py    ├──__init__.py    ├──__init__.pyc    ├──migrations    │├──0001_ initial.py    │├──0001_initial.pyc    │├──__init__.py    │└──__init__.pyc    ├──models.py    ├──mod Els.pyc    ├──tests.py    └──views.py4 directories, files

Modify helloworld/testmodel/models.py:

Create a model

# models.pyfrom django.db Import models Class Test (models. Model):    name = models. Charfield (max_length=20) 

Modify settings.py

Installed_apps = (    ' django.contrib.admin ',    ' Django.contrib.auth ',    ' Django.contrib.contenttypes ',    ' django.contrib.sessions ',    ' django.contrib.messages ', ' Django.contrib.staticfiles ', ' Testmodel ', # Add this item)       

Execute the following command

$ python manage.py migrate   # CREATE TABLE structure $ python manage.py makemigrations testmodel  # Let Django know we have some changes in our model $ python manage.py Migrate Testmodel   # CREATE TABLE structure

Database operations

Modify helloworld/helloworld/urls.py

From Django.conf.urls import *from . Import view,testdb urlpatterns = [    url (r ' ^hello$ ', View.hello),    URL (r ' ^testdb$ ', Testdb.testdb),]   

Create helloworld/helloworld/testdb.py

#-*-Coding:utf-8-*-from django.http import HttpResponse from testmodel.models import Test # database Operation def TestDB (R Equest):    test1 = Test (name= ' Runoob ')    test1.save ()    return HttpResponse ("<p> data added successfully! </p> ")  

Then enter IP:8000/TESTDB in the browser

Python's Web application framework--django

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.