Getting Started with the--django foundation of web frameworks

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. Django is an open-source Web application framework written by Python. The MVC framework pattern was adopted, i.e. model M, view V and Controller C. It was originally developed to manage some of the news content-based websites of the Lawrence Publishing Group, namely CMS (Content management system) software. and was released in July 2005 under the BSD license. The framework is named after the Belgian gypsy jazz guitarist Django Reinhardt.

Basic Configuration

First, create a Django program

    • Terminal command creation: Django-admin statproject obj_name

    • The IDE creates a Django program, essentially automatically executing the above command

Create the project directory structure:

Other common commands:

   Python manage.py runserver 0.0.0.0 python manage.py startapp appname python manage.py syncdb python manage.py makemigra tions python manage.py migrate python manage.py createsuperuser

Second, the configuration file

settings.py

1. Database

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

Since the Django internal connection to MySQL is using the MySQLdb module, and there is no such module in the Python3, it is necessary to use Pymysql instead

Import Pymysqlpymysql.install_as_mysqldb ()

2. Templates

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

3. static files

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

1. Each routing rule corresponds to a function in the view

URL (r ' ^index/(\d*) ', views.index), url (r ' ^manage/(? p<name>\w*)/(? p<id>\d*) ', views.manage), url (r ' ^manage/(? p<name>\w*) ', views.manage,{' id ': 333}),

2, according to the app to classify the rules

URL (r ' ^web/', include (' Web.urls ')),

  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.

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.

Template language:

  • {{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}}

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_safefrom Django.template.base import resolve_variable, Node, templatesyntaxerror  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 ',
Form

The form in Django typically has two functions:

    • Enter HTML
    • Validating user input
#!/usr/bin/env python#-*-coding:utf-8-*-import refrom Django import formsfrom django.core.exceptions import Validation Errordef mobile_validate (value): Mobile_re = Re.compile (R ' ^ (13[0-9]|15[012356789]|17[678]|18[0-9]|14[57]) [0-9]{8}$ ' If not Mobile_re.match (value): Raise ValidationError (' Phone number format error ') Class PublishForm (forms. Form): User_type_choice = ((0, U ' normal user '), (1, U ' advanced user '),) User_type = forms.                                                                  Integerfield (Widget=forms.widgets.select (Choices=user_type_choice, Attrs={' class ': "Form-control"})) title = forms. Charfield (max_length=20, min_length=5, error_messages={' Required ': U                                            ' Title cannot be empty ', ' min_length ': U ' title is at least 5 characters ', ' Max_length ': U ' title up to 20 characters '}, widget=forms.                      TextInput (attrs={' class ': "Form-control",                                    ' Placeholder ': U ' title 5-20 characters '}) Memo = forms. Charfield (Required=false, max_length=256, Widget=forms.widgets.textare A (attrs={' class ': "Form-control no-radius", ' placeholder ': U ' detailed description ', ' Rows ': 3})) phone = forms.                            Charfield (Validators=[mobile_validate,], error_messages={' Required ': U ' phone cannot be empty '}, Widget=forms. TextInput (attrs={' class ': "Form-control", ' placeholder ': U ' mobile number '} ) Email = forms.                            Emailfield (Required=false, error_messages={' Required ': U ' mailbox cannot be empty ', ' invalid ': U ' mailbox format error '}, Widget=forms. TextInput (attrs={' class ': "Form-control", ' placeholder ': U ' mailbox ')) def __init__ (self, *args, **kwargs): Super ( Sampleimportform, self). __init__ (*args, **kwargs) self.fields[' IDC '].widget.choices = models. IDC.objects.all (). order_by (' id '). values_list(' id ', ' Display ') self.fields[' business_unit '].widget.choices = models. BusinessUnit.objects.all (). order_by (' id '). values_list (' id ', ' name ') Forms

  

def publish (Request):    ret = {' status ': False, ' data ': ', ' Error ': ', ' Summary ': '}    if Request.method = = ' POST ':        request_form = publishform (Request. POST)        if Request_form.is_valid ():            request_dict = Request_form.clean ()            print request_dict            ret[' Status '] = True        else:            error_msg = Request_form.errors.as_json ()            ret[' error '] = json.loads (error_msg)    return HttpResponse (Json.dumps (ret))

Extension: Modelform

When you use the model and form, you need to define the field and specify the type, and you can omit the definition of the From field by Modelform

Class Adminmodelform (forms. Modelform):          class Meta:        model = models. Admin        #fields = ' __all__ ' fields        = (' username ', ' email ')                  widgets = {            ' email ': forms. Passwordinput (attrs={' class ': "Alex"}),        }
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 = (    ' 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)

  

Getting Started with the--django foundation of web frameworks

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.