PYthon's web framework is Django, Tornado, Flask, and so on, Django compared with other web frameworks its advantages: chatty, the framework itself integrates ORM, model binding, template engine, caching, session and many other functions.
Basic Configuration
First, create a Django program
- Terminal command: Django-admin startproject sitename
- When the IDE creates a Django program, it is essentially automating the above command
Python manage.py runserver 0.0.0.0
Python manage.py Startapp AppName
To perform a table-making operation after the completion class is created
Python manage.py makemigrations
Python manage.py Migrate
Second, the program directory
Iii. Configuration Files
1. setting file configuration default database connection
DATABASES = {' default ': ' ENGINE ': ' Django.db.backends.mysql ', ' NAME ': ' dbname ', ' USER ': ' Root ', ' PASSWORD ': ' xxx ', ' HOST ': ', ' PORT ': ', }}
# because the Django internal connection to MySQL is using the MySQLdb module, and the Python3 does not have this module, so you need to use Pymysql instead of # settings placed in the same name as the project in the configuration __init__.py file import Pymysqlpymysql.install_as_mysqldb ()
2. Template
#添加模版文件路径
Template_dirs = ( os.path.join (base_dir, ' templates '), )
3. static files
#配置静态文件路径, Css,js and a variety of modules will be in the secondary file directory
Staticfiles_dirs = ( os.path.join (base_dir, ' static '), )
Routing system
1. Single Route Correspondence
URL (r ' ^index$ ', Views.index),
2. Regular-based routing
URL (r ' ^index/(\d*) ', views.index), url (r ' ^manage/(? p<name>\w*)/(? p<id>\d*) ', views.manage),
3. Add additional parameters
URL (r ' ^manage/(? p<name>\w*) ', views.manage,{' id ': 333}),
4. Set the name for the route map
URL (r ' ^home ', views.home, Name= ' h1 '), url (r ' ^index/(\d*) ', Views.index, name= ' H2 '),
After you set the name, you can call it in a different place, such as:
- Template used to generate URL {% url ' h2 ' 2012}
- The function uses the Generate URL reverse (' H2 ', args= (2012,)) path: Django.urls.reverse
- Use the Get URL custom Get_absolute_url () method in model
classNewType (models. Model): Caption= Models. Charfield (max_length=16) defGet_absolute_url (self):"""generate a URL app for each object: Generate a View-detailed URL in the object list and use this method!!! : Return:""" #return '/%s/%s '% (self._meta.db_table, self.id) #or fromDjango.urlsImportReversereturnReverse'Newtype.detail', kwargs={'nid': Self.id})
View Code
5, according to the app routing rules classification
#路由分发
URL (r ' ^web/', include (' Web.urls ')),
6. Namespaces
A. project.urls.py
From django.conf.urls import url,includeurlpatterns = [ url (R ' ^a/', include (' App01.urls ', namespace= ' author-polls '), url (r ' ^b/', include (' App01.urls ', namespace= ' publisher-polls ')),]
B. app01.urls.py
From django.conf.urls import urlfrom app01 Import viewsapp_name = ' app01 ' urlpatterns = [ url (r ' ^ (? p<pk>\d+)/$ ', views.detail, name= ' detail ')]
C. app01.views.py
def detail (Request, PK): print (Request.resolver_match) return HttpResponse (PK)
After you have defined the URL with the namespace, use name to generate the URL as follows:
- v = reverse (' app01:detail ', kwargs={' PK ': 11})
- {% url ' app01:detail ' pk=12 pp=99%}
The routing system in Django differs from the framework of other languages in that the URL for each request in Django has a route map so that the request can be handed to the function in the view for processing. Most other web frameworks are a route map for a class of URL requests, which makes the routing system concise.
Develop a dynamic routing system for Django with the reflection mechanism demo
Template
1, the implementation of the template
Template creation process, for the template, in fact, is to read the template (which nested template tags), and then insert the data obtained in the model into the template, and finally return the information to the user.
def current_datetime (Request): Now = Datetime.datetime.now () html = "<html >< Body > It's now%s.</body></html>'% now return HttpResponse (HTML)
View Code
From django Import templatet = template. Template (' My name is {{name}}}. ') c = Template. Context ({' name ': ' Adrian '}) print T.render (c)
View Code
Import datetimefrom Django Import templateimport djangodemo.settings now = Datetime.datetime.now () fp = open (settings. base_dir+ '/templates/home/index.html ') t = template. Template (Fp.read ()) fp.close () HTML = t.render (template. Context ({' Current_date ': now}) return HttpResponse (HTML
View Code
From Django.template.loader import get_templatefrom django.template import contextfrom django.http Import Httpresponseimport datetime def current_datetime (Request): Now = Datetime.datetime.now () t = get_template (' Current_datetime.html ') html = T.render (Context ({' Current_date ': now}) return HttpResponse (HTML)
View Code
Return Render_to_response (' account/login.html ', Data,context_instance=requestcontext (Request))
View Code
2. Template language
Templates also have their own language, which enables data presentation
- {{Item}}
- {% for item in item_list%} <a>{{item}}</a> {% ENDFOR%}
Forloop.counter
Forloop.first
Forloop.last
- {% if Ordered_warranty%} {% Else%} {% ENDIF%}
- Motherboard: {% block title%}{% Endblock%}
Sub-board: {% extends "base.html"%}
{% block title%} {% Endblock%}
- How to help:
{{item.event_start|date: "Y-m-d h:i:s"}}
{{bio|truncatewords: ' 30 '}}
{{My_list|first|upper}}
{{Name|lower}}
3. Custom Simple_tag
A. Create the Templatetags module in the app
b, create any. py file, such as: xx.py
#!/usr/bin/env python#coding:utf-8from Django Import templatefrom django.utils.safestring import Mark_safe Register = template. Library () @register. Simple_tagdef my_simple_time (v1,v2,v3): return v1 + v2 + v3 @register. Simple_ Tagdef My_input (id,arg): result = "<input type= ' text ' id= '%s ' class= '%s '/>"% (Id,arg,) return Mark_safe ( Result
C. Import the xx.py file name created before using the custom Simple_tag HTML file
{% load xx%}
D. Using Simple_tag
{% My_simple_time 1 2 3%} {% my_input ' id_username ' Hide '%}
E, configure the current app in Settings, or Django can't find a custom Simple_tag
Installed_apps = ( ' django.contrib.admin ', ' Django.contrib.auth ', ' django.contrib.contenttypes ', ' django.contrib.sessions ', ' django.contrib.messages ', ' django.contrib.staticfiles ', ' app01 ',
Middleware
In Django's middleware (middleware), in Django, the middleware is actually a class, and after the request arrives and ends, Django executes the appropriate method in the middleware at the right time according to its own rules.
In the settings module of the Django Project, there is a middleware_classes variable, each of which is a middleware, such as.
Authentication class in auth.py file under folder Wupeiqi/middleware under the same directory as mange.py
Four methods can be defined in a middleware, namely:
- Process_request (Self,request)
- Process_view (self, request, callback, Callback_args, Callback_kwargs)
- Process_template_response (Self,request,response)
- Process_exception (self, request, exception)
- Process_response (self, request, response)
The return value of the above method can be none and the Httpresonse object, and if none, continue down according to the Django-defined rule, and if it is a Httpresonse object, return the object directly to the user.
Custom Middleware
1. Create a middleware class
Class Requestexeute (object): def process_request (self,request): pass def process_view (self, request, Callback, Callback_args, Callback_kwargs): i =1 pass def process_exception (self, request, exception): Pass def process_response (self, request, response): return response
2. Register Middleware
middleware_classes = ( ' django.contrib.sessions.middleware.SessionMiddleware ', ' Django.middleware.common.CommonMiddleware ', ' django.middleware.csrf.CsrfViewMiddleware ', ' Django.contrib.auth.middleware.AuthenticationMiddleware ', ' Django.contrib.auth.middleware.SessionAuthenticationMiddleware ', ' Django.contrib.messages.middleware.MessageMiddleware ', ' Django.middleware.clickjacking.XFrameOptionsMiddleware ', ' Wupeiqi.middleware.auth.RequestExeute ',)
Admin
Django Amdin is a back-Office Admin page that Django provides, and the Admin page provides perfect HTML and CSS so that after you create a database table through model, you can add and modify data, while using Django Admin requires the following steps:
- Create a background administrator
- Configure URLs
- Registering and configuring the Django Admin Background Management page
1. Create a background administrator
Python manage.py Createsuperuser
2, configure the background management URL
URL (r ' ^admin/', include (Admin.site.urls))
3. Registering and configuring the Django Admin Background Management page
A. Perform the following configuration in admin
From django.contrib Import admin from app01 import models Admin.site.register (models. usertype) Admin.site.register (models. UserInfo) Admin.site.register (models. UserGroup) Admin.site.register (models. Asset)
B. Set the data table name
Class Usertype (models. Model): name = models. Charfield (max_length=50) class Meta: verbose_name = ' user type ' verbose_name_plural = ' user type '
C, after opening the table, set the default display, you need to make the following configuration in model
Class Usertype (models. Model): name = models. Charfield (max_length=50) def __unicode__ (self): return Self.name
From django.contrib Import admin from APP01 import models class Userinfoadmin (admin. Modeladmin): list_display = (' username ', ' password ', ' email ') Admin.site.register (models. usertype) Admin.site.register (models. Userinfo,userinfoadmin) Admin.site.register (models. UserGroup) Admin.site.register (models. Asset)
D. Add search function to data table
From django.contrib Import admin from APP01 import models class Userinfoadmin (admin. Modeladmin): list_display = (' username ', ' password ', ' email ') Search_fields = (' username ', ' email ') Admin.site.register (models. usertype) Admin.site.register (models. Userinfo,userinfoadmin) Admin.site.register (models. UserGroup) Admin.site.register (models. Asset)
E, add quick filter
From django.contrib Import admin from APP01 import models class Userinfoadmin (admin. Modeladmin): list_display = (' username ', ' password ', ' email ') Search_fields = (' username ', ' email ') list_ Filter = (' username ', ' email ') Admin.site.register (models. usertype) Admin.site.register (models. Userinfo,userinfoadmin) Admin.site.register (models. UserGroup) Admin.site.register (models. Asset)
Django Database Operation ORM