Python's Django Beginner

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

2. Program Directory

1.settings.py Placement Profile

1) database

1 DATABASES = {2 ' default ': {3 ' ENGINE ': ' Django.db.backends.mysql ',4 ' NAME ': ' dbname ',5 ' USER ': ' Root ',6 ' PASSWORD ': ' xxx ',7 ' HOST ': ',8 ' PORT ': ',9     }Ten } One 1 A 2 - 3 - 4 the 5 - 6 - # because the Django internal connection MySQL uses the MySQLdb module, but the Python3 does not have this module, therefore needs to use the Pymysql to replace -    + # The following settings are placed in the CONFIG. __init__.py file with the same name as Project -    + Import Pymysql APymysql.install_as_mysqldb ()
Database

2) Template

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

3) static files

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

2.urls.py Storage Routing System (map)

  1) Each route 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. Develop a dynamic routing system for Django through the Reflection mechanism Demo: Click to download

3.wsgi.py

Let you do configuration: WSGI There are multiple kinds of uwsgi and WSGI, you use that kind of wsgi to run Django, generally do not have to change only when you use the

4.manage.py

Is the Django startup hypervisor.

Above configuration file, if it is a beginner do not modify after the creation of project, because it involves a lot of configuration files need to be modified

3. Project and App Concepts

We are currently creating a project,project below can have a lot of apps, what is the principle of it!

The project we created is a big project, and there are a lot of features: (a project has multiple apps, in fact he's a sort of big project for You)

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

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

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"}),        }
Model

So far, when our program involves database-related operations, we usually do this:

    • Create databases, Design table structures and fields
    • Use MYSQLDB to connect to a database and write data access layer code
    • The business logic layer to invoke the data access layer to perform database operations
Import mysqldb def GetList (SQL):    db = MySQLdb.connect (user= ' root ', db= ' wupeiqidb ', passwd= ' 1234 ', host= ' localhost ')    cursor = db.cursor ()    cursor.execute (sql)    data = Cursor.fetchall ()    db.close ()    return Data def getsingle (SQL):    db = MySQLdb.connect (user= ' root ', db= ' wupeiqidb ', passwd= ' 1234 ', host= ' localhost ')    cursor = db.cursor ()    cursor.execute (sql)    data = Cursor.fetchone ()    db.close ()    return data
View Code

Django uses a new approach, namely: Relational object Mapping (object relational Mapping, or ORM).

Php:activerecord

Java:hibernate

C#:entity Framework

Django follows the code Frist principle of automatically generating database tables based on classes defined in your code.

1, create the model, then you can create a database table according to the model

From django.db import Models  class UserInfo (models. Model):    name = models. Charfield (max_length=30)    email = models. Emailfield ()    memo = models. TextField ()
1, models. Autofield self-increment = Int (11) If not, the default is to generate a column named ID, and if you want to display a custom self-increment column, you must set the column as the primary key primary_key=true. 2, models. The Charfield string field must be max_length parameter 3, models. Booleanfield Boolean type =tinyint (1) cannot be empty, blank=true4, models. Comaseparatedintegerfield a comma-separated number =varchar inherits Charfield, so the parameter 5, models must be max_lenght. Datefield Date type dates for parameters, Auto_now = True, the time is updated for each update, and Auto_now_add is only the first time that the update is created, and then the updates are no longer changed. 6, models. Datetimefield Date type datetime with Datefield parameter 7, models. Decimal decimal Decimal type = decimal must specify integer digits max_digits and decimal places DECIMAL_PLACES8, models. Emailfield String type (regular expression mailbox) =varchar Regular Expression 9, models for strings. Floatfield floating-point type = Double10, models. Integerfield Plastic 11, models. Bigintegerfield Long Plastic integer_field_ranges = {' Smallintegerfield ': ( -32768, 32767), ' Integerfield ': (-2147483648, 2     147483647), ' Bigintegerfield ': ( -9223372036854775808, 9223372036854775807), ' Positivesmallintegerfield ': (0, 32767), ' Positiveintegerfield ': (0, 2147483647),}12, models. Ipaddressfield String type (IP4 regular expression) 13, models.  GenericipaddressfieldString types (IP4 and IP6 are optional) parameters protocol can be: both, IPv4, IPv6 validation, according to set error 14, models. Nullbooleanfield is allowed to be null for Boolean type 15, models. Positiveintegerfiel is Integer16, models. Positivesmallintegerfield is SmallInteger17, models. Slugfield minus, underscore, letter, number 18, models. The fields in the Smallintegerfield digital database are: tinyint, smallint, int, bigint19, models. TextField string =longtext20, models. Timefield time hh:mm[:ss[.uuuuuu]]21, models. Urlfield string, address regular expression 22, models. Binaryfield binary 23, models. ImageField Pictures 24, models. Filepathfield file
more Fields

1, whether the field in the Null=true database can be empty 2, Blank=true Django Admin to add data when you can allow null value 3, Primary_key = False primary key, after the Autofield set the primary key, will replace the original self-increment ID column 4, Auto_now and Auto_now_add auto_now   automatically created---whether added or modified, is the time of the current operation Auto_now_add  automatically created---is always created at the time of 5, Choicesgender_ CHOICE = (U '        M ', U ' Male '),        (U ' F ', U ' Female '),    gender = models. Charfield (max_length=2,choices = gender_choice) 6, Max_length7, default value 8, verbose_name admin field display name 9, name|db_ Field name in column database 10, unique=true not allowed to repeat 11, Db_index = True Database index 12, editable=true in admin can edit 13, error_messages=none error prompt 1 4, Auto_created=false automatically create 15, Help_text in admin tips help information 16, validators=[]17, upload-to
More Parameters

2. Connecting table relationship:

    • A pair of more, models. ForeignKey (Colordic)
    • One on one, models. Onetoonefield (Onemodel)
    • Many-to-many, authors = models. Manytomanyfield (Author)

Application Scenarios:

      • One to one: when you create a row of data in a table, there is a single-selection drop-down box (the contents of the drop-down box are used once and disappear).
        For example, a table containing 10 columns of data holds relevant information, and after a period of time, 10 columns do not meet the requirements and need to add 5 columns of data to the original table.
      • One-to-many: when a row of data is created in a table, there is a single-selection drop-down box (which can be selected repeatedly).
        For example: When creating user information, you need to select a user type "ordinary user" "Gold user" "Platinum User" and so on.
      • Many-to-many: a row of data is created in a table, and there is a drop-down box that you can choose from.
        For example, to create user information, you need to specify multiple hobbies for the user.

3. Database operation

      • Add: Create an instance and call save
      • Update: A. Get instance, then Sava;b.update (Specify column)
      • Delete: A. Filter (). Delete (); B.all (). Delete ()
      • Get: A. Single =get (id=1); b. all = All ()
      • Filtering: Filter (name= ' xxx '), filter (name__contains= ");(id__in = [[+]]);
        Icontains (case-insensitive like), StartsWith and EndsWith, and range (sqlbetween query) ' GT ', ' in ', ' isnull ', ' endswith ', ' contains ', ' lt ', ' StartsWith ', ' iendswith ', ' icontains ', ' range ', ' istartswith '
      • Sort: order_by ("name") =asc; order_by ("-name") =desc
      • Return to article n-m: article n [0]; top two [0:2]
      • Specify mappings: Values
      • Quantity: Count ()
      • Aggregation: From django.db.models import Min,max,sum Objects.all (). Aggregate (Max (' guest_id '))
      • Raw SQL
cursor = Connection.cursor () cursor.execute ("' Select DISTINCT first_name ROM people_person WHERE last_name =%s" "", [' Len Non ']) row = Cursor.fetchone ()

Python's Django Beginner

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.