Web Framework Django Basics

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.

First, the basic configuration

1. 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

2. Program Directory

3. Configuration files

3.1 Database

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

由于Django内部连接MySQL时使用的是MySQLdb模块,而python3中还无此模块,所以需要使用pymysql来代替 

如下设置放置的与project同名的配置的 __init__.py文件中
Import Pymysqlpymysql.install_as_mysqldb ()

3.2 Templates

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

3.3 Static files

Staticfiles_dirs = (        os.path.join (base_dir, ' static '),    )

Second, the 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
Class NewType (models. Model):    caption = models. Charfield (max_length=16)    def get_absolute_url (self): ""        generates a URL app for each object        : Generates a view-detailed URL in the object list, Use this method!!!        : Return: "" "        # return '/%s/%s '% (self._meta.db_table, self.id)        # or from        django.urls import Reverse        return reverse (' 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

6.1 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 ')),]

6.2 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 ')]

6.3 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

Third, the 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 = "

  

From django Import templatet = template. Template (' My name is {{name}}}. ') c = Template. Context ({' name ': ' Adrian '}) print T.render (c)

  

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)

  

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)

  

Return Render_to_response (' account/login.html ', Data,context_instance=requestcontext (Request))

  

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 ',

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

Iv. 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 ',)

Five, 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)

Web Framework Django Basics

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.