"Python Learning Path"--day20 (Django)

Source: Internet
Author: User

Python's web framework has a variety of Django, Tornado, Flask and more, and Django has its advantages over other web frameworks: Chatty, the framework itself integrates ORM, model binding, template engine, caching, session and many more.

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

Other common commands:

Python manage.py runserver 0.0.0.0
Python manage.py Startapp AppName
Python manage.py syncdb
Python manage.py makemigrations
Python manage.py Migrate

Python manage.py Createsuperuser

Second, the program directory

Iii. Configuration Files

1. Database

DATABASES = {'    default ': '    ENGINE ': ' Django.db.backends.mysql ',    ' NAME ': ' dbname ',    ' USER ': ' Root ',    ' PASSWORD ': ' xxx ', '    HOST ': ',    ' PORT ': ',    }}

Note:

# because the Django internal connection MySQL is using the MySQLdb module, and Python3 does not have this module, so you need to use Pymysql instead of  # settings placed in the same name as the configuration of project __init__.py file  Import Pymysqlpymysql.install_as_mysqldb ()

2. Template

Template_dirs = (        os.path.join (base_dir, ' templates '),    )

3. static files

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= -) def get_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.urls Import ReversereturnReverse'Newtype.detail', kwargs={'nid': Self.id})

Gets the URL information for the successful request match: Request.resolver_match

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,include urlpatterns = [    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 views app_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 through the Reflection mechanism Demo: Click to download

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):     = Datetime.datetime.now ()    "" % now return HttpResponse (HTML)    
from = template. Template ('My name is {{name}}}. '  = template. Context ({'name''Adrian'}) print T.render (c)
View Code
Import datetime  from  == open (settings. base_dir+'/templates/home/index.html'== T.render (template. Context ({'current_date': now})return HttpResponse (HTML
View Code
 from django.template.loader Import Get_template  from django.template Import Context  from django.http Import httpresponseimport datetime def current_datetime (Request):     = Datetime.datetime.now ()    = get_template ('current_datetime.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-8 from the Django Import template from Django.utils.safestring Import mark_safe   = template. Library ()   @register. Simple_tagdef my_simple_time (v1,v2,v3):    return  v1 + v2 + v3   @register. Simple_tagdef my_input (id,arg):     " <input type= ' text ' id= '%s ' class= '%s '/> " %(id,arg,)    return mark_safe (Result)
View Code

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',)
View Code

See the documentation for more information: https://docs.djangoproject.com/en/1.10/ref/templates/language/

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)
View Code

B. Set the data table name

class usertype (models. Model):    = models. Charfield (max_length=)      class  Meta:        ' user type  "User type  "        
View Code

C, after opening the table, set the default display, you need to make the following configuration in model

class usertype (models. Model):    = models. Charfield (max_length=)      def        __unicode__ (self):return self.name
View Code
 from django.contrib Import Admin    from APP01 Import  models  class  userinfoadmin (admin. Modeladmin):    = ('username'password' ' Email ' )    Admin.site.register (models. usertype) Admin.site.register (models. Userinfo,userinfoadmin) Admin.site.register (models. UserGroup) Admin.site.register (models. Asset)
View Code

D. Add search function to data table

 fromdjango.contrib Import Admin fromAPP01 Import Modelsclassuserinfoadmin (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)
View Code

E, add quick filter

 fromdjango.contrib Import Admin fromAPP01 Import Modelsclassuserinfoadmin (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)
View Code

Reference Links:

Http://www.cnblogs.com/wupeiqi/articles/5237704.html

"Python Learning Path"--day20 (Django)

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.