# # # directory:

  • Django Tutorial part 1 – Django views and urls
  • Django Tutorial ii – Django views with URL progression
  • Django Tutorial (3) – Django Forms
  • Django Tutorial (4) – Django templates and progression
  • Django models (databases) and common Django Query methods
  • Django Tutorial 5 – Upload and display
  • Django Tutorial part 1 – Build a simple blog system
  • Django Hands-on (Part 2) – Create a course selection system

The Form component in Django provides the following functions:

  1. Generating HTML tags
  1. Validate user data (display error message)
  2. The HTML Form submission retains the data from the last submission
  3. Initialize the page display

When creating the Form class, it mainly involves [field] and [plug-in]. The field is used to verify the user request data, and the plug-in is used to automatically generate HTML.

####1.Django’s built-in fields are as follows:

  • Field:
Required =True, whether empty widget=None is allowed, HTML plug-in label=None, used to generate label labels or display content Initial =None, initial value help_text=' ', help message (displayed next to the tag) error_messages=None, error message {'required': 'Cannot be empty'.'invalid': 'Formatting error'} show_hidden_initial=False, validators=[], localize=False, Whether to support localization (different languages are displayed according to different language regions) Disabled =False whether to modify label_suffix=None Label content suffixCopy the code
  • CharField(Field)
Max_length =None, maximum length min_length=None, minimum length strip=True Whether to remove blank user inputCopy the code
  • IntegerField(Field), FloatField(IntegerField)
Max_value =None, maximum min_value=None, minimum valueCopy the code
  • DecimalField(IntegerField), for example, involving money calculations that retain two decimal places
Max_value =None, Max min_value=None, min max_digits=None, total length decimal_places=None, decimal lengthCopy the code
  • BaseTemporalField(Field)
Input_formats =None Time formattingCopy the code
DateField(BaseTemporalField) format: 2015-09-01 TimeField(BaseTemporalField) format: 11:12 DateTimeField(BaseTemporalField) format: 2015-09-01 DurationField(Field) Interval :% D %H:%M:%S.%fCopy the code
  • RegexField(CharField)
Regex, custom regular expression max_length=None, maximum length min_length=None, minimum length error_message=None, ignored, error_messages={'invalid': '... '}

Copy the code

EmailField(CharField) …

  • FileField(Field)
Allow_empty_file =False Whether empty files are allowedCopy the code
  • ImageField(FileField)
. Note: encType = is used in the form from PIP install Pillow"multipart/form-data"- view obj = MyForm(request.post, request.files)Copy the code

URLField(Field)… BooleanField(Field)… NullBooleanField(BooleanField)…

  • ChoiceField(Field)
Choices =(), for example: choices=((0,'Shanghai'), (1,'Beijing'),) required=True, whether widget=None, plug-in, default select plug-in label=None, label content initial=None, initial value help_text=' ', help tipsCopy the code
  • TypedChoiceField(ChoiceField)
Coerce = lambda val: val performs a conversion on the selected value, using the lambda function to implement empty_value=' 'The default value for nullCopy the code
  • MultipleChoiceField(ChoiceField)

  • TypedMultipleChoiceField(MultipleChoiceField)

Coerce = lambda VAL: val converts each selected value empty_value=' 'The default value for nullCopy the code
  • ComboField(Field)
Fields.Com boField(fields=[fields.charfield (max_length=20), fields.emailfield (),])Copy the code
  • MultiValueField(Field) : an abstract class that aggregates multiple dictionaries to match a value

  • SplitDateTimeField(MultiValueField)

Input_date_formats =None, list of formats: ['%Y--%m--%d'.'%m%d/%Y'.'%m/%d/%y'] input_time_formats=None List of formats: ['%H:%M:%S'.'%H:%M:%S.%f'.'%H:%M']

Copy the code
  • FilePathField(ChoiceField) file option. Files under the directory are displayed on the page
Allow_folders =False allow_folders= True allow_folders=False allow_folders= True allow_folders=False allow_folders= True widget=None, label=None, initial=None, help_text=' '
Copy the code
  • GenericIPAddressField
protocol='both', both,ipv4,ipv6 SUPPORTED IP address format Unpack_ipv4 =False The ipv4 address is resolved. If: FFFF :192.0.2.1 is displayed, the value can be 192.0.2.1Copy the code
  • **SlugField(CharField) : ** Number, letter, underscore, minus (hyphen)

  • **UUIDField(CharField) : **UUID type

import uuid

# make a UUID based on the host ID and current time
>>> uuid.uuid1()    # doctest: +SKIP
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e')

# make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e')

# make a random UUID
>>> uuid.uuid4()    # doctest: +SKIP
UUID('16fd2706-8baf-433b-82eb-8c7fada847da')

# make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d')

# make a UUID from a string of hex digits (braces and hyphens ignored)
>>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}')

# convert a UUID to a string of hex digits in standard form
>>> str(x)
'00010203-0405-0607-0809-0a0b0c0d0e0f'

# get the raw 16 bytes of the UUID
>>> x.bytes
b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f'

# make a UUID from a 16-byte string
>>> uuid.UUID(bytes=x.bytes)
UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')
Copy the code
  • Built-in Django plugins:
TextInput(Input)  #input type="text"
NumberInput(TextInput)  # number input box
EmailInput(TextInput)  # mailbox input box
URLInput(TextInput)  # url input box
PasswordInput(TextInput)  # Password input box
HiddenInput(TextInput)  # Hide the input field
Textarea(Widget)  # textarea textarea
DateInput(DateTimeBaseInput)  # Date input box
DateTimeInput(DateTimeBaseInput)  # Date time input box
TimeInput(DateTimeBaseInput)  # Time input box
CheckboxInput  # boxes,
Select  # a drop-down box
NullBooleanSelect  # Non-empty Boolean drop-down box
SelectMultiple  # Multi-select drop-down box
RadioSelect  # single box
CheckboxSelectMultiple  # checkbox??
FileInput  # file upload
ClearableFileInput
MultipleHiddenInput  # More hidden input box
SplitDateTimeWidget  # Time split box (two input boxes)
SplitHiddenDateTimeWidget
SelectDateWidget
Copy the code
  • Commonly used selection plug-ins
# single radio, value string
# user = fields.CharField(
# initial=2,
# widget = widgets. RadioSelect (choices = ((1, "Shanghai"), (2, 'Beijing'),))
#)

# single radio, value string
# user = fields.ChoiceField(
# choices=(1, 'Shanghai '), (2,' Beijing '),),
# initial=2,
# widget=widgets.RadioSelect
#)

# single select, value is string
# user = fields.CharField(
# initial=2,
# widget = widgets. Select (choices = ((1, "Shanghai"), (2, 'Beijing'),))
#)

# single select, value is string
# user = fields.ChoiceField(
# choices=(1, 'Shanghai '), (2,' Beijing '),),
# initial=2,
# widget=widgets.Select
#)

Select * from list
# user = fields.MultipleChoiceField(
# choices=(1,' Shanghai '),(2,' Beijing '),),
# initial=[1,],
# widget=widgets.SelectMultiple
#)



# single checkbox
# user = fields.CharField(
# widget=widgets.CheckboxInput()
#)


# select checkbox, value is a list
# user = fields.MultipleChoiceField(
# initial=[2, ],
# choices=(1, 'Shanghai '), (2,' Beijing '),),
# widget=widgets.CheckboxSelectMultiple
#)
Copy the code

Django template addition, subtraction, multiplication, and division:

Django template addition: {{value | add: 10}} value = 5, return 15 Django template subtraction: {{value | add: - 10}} value = 5, return to 5, this is better understood, subtraction is to add a negative number multiplication Django template: {% widthratio 5 1 100 %} Widthratio requires three parameters. It uses parameter 1/ parameter 2* parameter 3, so to multiply, set parameter 2=1 to Django template division view sourceprint? {% widthratio 5 100 1 %} The code above says: 5/100*1, return 0.05, just set the third parameter to 1Copy the code

Use the Django Form to complete the request ###1. Jump to a different page depending on how the user fills out the Form. Create the app project name: djangoForm

2. Create folder djangoForm under app and create form form1.py

# -*- coding:utf8 -*-
from django.forms import Form
from django.forms import widgets  # plug-in
from django.forms import fields # field

class webpage(Form):
    page = fields.CharField()
Copy the code

3. Create the Templates folder under app and create different HTML pages

  • index.html
<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8"</title> </head> <body> <form action="" method="post"> {% csrF_token %} Please select the page to go to: {{web.page}} <inputtype="submit" value="Submit">

    </form>

</body>
</html>
Copy the code
  • page1.html
<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8"> <title>page1</title> </head> <body>Copy the code
  • page2.html
<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8"> <title>page2</title> </head> <body> page2: one inch of love, one inch of ashes </body> </ HTML >Copy the code

4. Create views.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render,redirect
from django.http import HttpResponse
from djangoform import form1

# Create your views here.


def indexPage(request):
    if request.method == "GET":
        webPage=form1.webpage()
        return render(request,'index.html', {'web':webPage})

    elif request.method == "POST":
        webPage = form1.webpage(request.POST,request.FILES)
        if webPage.is_valid():
            values = webPage.clean()
            print(values)
            if values['page'] = ='1':
                return render(request, 'page1.html', {'web': webPage})
            elif values['page'] = ='2':
                return render(request, 'page2.html', {'web': webPage})
            elif values['page'] = ='3':
                return render(request, 'page3.html', {'web': webPage})
        else:
            errors = webPage.errors
            print(errors)
        return render(request, 'index.html', {'web': webPage})
    else:
        return redirect('http://www.baidu.com')




def index(request):
    if request.method == "GET":
        obj = forms.MyForm()  Render the tag in the form on the page without a value
        return render(request, 'index.html', {'form': obj})

    elif request.method == "POST":
        obj = forms.MyForm(request.POST, request.FILES)  Pass the data submitted by post as an argument to the custom Form class
        if obj.is_valid():  # obj.is_valid() returns a bool, True if the check passes, False otherwise
            values = obj.clean()  Get all the processed data in the form of key-value pairs
            print(values)
        else:
            errors = obj.errors  # get failed error message, which encapsulates all objects
            print(errors)
        return render(request, 'index.html', {'form': obj})
    else:
        return redirect('http://www.baidu.com')
Copy the code

5. Define view function-related ·urls.py·

from django.conf.urls import include, url
from django.contrib import admin
from . import views

urlpatterns = [
    url(r'^page/',views.indexPage,),
]
Copy the code

6. Add our newly defined app to INSTALL_APPS and urls in settings.py, as described in Django tutorial 1 – Django Views and urls

Effect display:

##2. Print the 9*9 times table on the web page

  • home.html
<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8"> <title> multiplication table </title> </head> <body> {%for i in list %}
        {% for j in list %}
            {% if j <= i %}
                {{i}}*{{j}}={% widthratio j 1 i %}
            {% endif %}
        {% endfor %}<br>
    {% endfor %}



</body>
</html>
Copy the code
  • views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render

# Create your views here.Def home (request) : list = [1,2,3,4,5,6,7,8,9,]return render(request,'home.html', {'list':list})
Copy the code
  • urls.py
from django.conf.urls import url
from . import views

urlpatterns=[
    url(r'^home/$',views.home,name='home', a)]Copy the code

Effect display:

##3. Print an even number between 1 and 100 on a web page

>>> map(str, range(5))           STR for range(5)
['0'.'1'.'2'.'3'.'4']        # return list
>>> def add(n):return n+n
... 
>>> map(add, range(5))           Add to range(5)
[0, 2, 4, 6, 8]
>>> map(lambda x:x+x,range(5))   Lambda function, term + itself
[0, 2, 4, 6, 8]
>>> map(lambda x:x+1,range(10))  Lambda function, plus 1
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> map(add,'zhoujy')            
['zz'.'hh'.'oo'.'uu'.'jj'.'yy']

The length of each sequence must be the same; otherwise, an error will be reported:
>>> def add(x,y):return x+y
... 
>>> map(add,'zhoujy'.'Python')
['zP'.'hy'.'ot'.'uh'.'jo'.'yn']
>>> def add(x,y,z):return x+y+z
... 
>>> map(add,'zhoujy'.'Python'.'test')     The length of #'test' is smaller than the other two
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: add() takes exactly 2 arguments (3 given)

>>> map(add,'zhoujy'.'Python'.'testop')
['zPt'.'hye'.'ots'.'uht'.'joo'.'ynp']
Copy the code
  • views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render

# Create your views here.

def even(request):
    list = map(str,range(100))  STR for range(100)
    return render(request,'even.html', {'list':list})
Copy the code
  • urls.py
from django.conf.urls import url
from . import views

urlpatterns=[
    url(r'^even/$',views.even,name='even', a)]Copy the code
  • even.html
<! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8"> <title> even numbers between 1 and 100 </title> </head> <body> {%for item in list %}
    {% if forloop.counter|divisibleby:2 %}{{forloop.counter}} {% if not forloop.last %},{% endif %} {% endif %}
    {% endfor %}



</body>
</html>
Copy the code

The effect is as follows:

#4. Custom validation validation rules

  • Method 1: Customize validators in the field to design regular matches
from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.validators import RegexValidator

class MyForm(Form):
    user = fields.CharField(
        validators=[RegexValidator(r'^ [0-9] + $'.'Please enter a number'), RegexValidator(r'^ 159 [0-9] + $'.'Numbers must start with 159') ",Copy the code
  • Method 2: Custom rule functions handle data
import re
from django.forms import Form
from django.forms import widgets
from django.forms import fields
from django.core.exceptions import ValidationError


# Custom validation rules
def mobile_validate(value):
    mobile_re = re.compile(r'^ (13 15 [012356789] [0-9] | | 17 [678] 18 [0-9] | | 14 [57]) [0-9] {8} $')
    if not mobile_re.match(value):
        raise ValidationError('Wrong format of mobile number')


class PublishForm(Form):


    title = fields.CharField(max_length=20,
                            min_length=5,
                            error_messages={'required': 'Title cannot be empty'.'min_length': 'Title minimum of 5 characters'.'max_length': 'Headings of up to 20 characters'},
                            widget=widgets.TextInput(attrs={'class': "form-control".'placeholder': 'Title 5-20 characters'}))


    # Use custom validation rules
    phone = fields.CharField(validators=[mobile_validate, ],
                            error_messages={'required': 'Phone can't be empty'},
                            widget=widgets.TextInput(attrs={'class': "form-control".'placeholder': u'Mobile number'}))

    email = fields.EmailField(required=False,
                            error_messages={'required': u'Mailbox cannot be empty'.'invalid': u'Email format error'},
                            widget=widgets.TextInput(attrs={'class': "form-control".'placeholder': u'email'}))
Copy the code