Django Form Forms

Source: Internet
Author: User

Form Introduction

In summary, the main functions of the form component are as follows:

Generate HTML tags available for a page

Verifying the data submitted by the user

Keep Last input

Prompt for error messages

Normal mode handwriting registration function views.py
def register (Request):    Name_error = '    if Request.method = = ' POST ':        user = Request. Post.get (' user ')        pwd = Request. Post.get (' pwd ')        if Len (user) < 6:            Name_error = ' username Too short '        else:            return HttpResponse (' registration successful ')    return render (Request, ' register.html ', {' Name_error ': Name_error})
Register.html
<! DOCTYPE html>Use the form component to implement the registration function views.py

Define the good one RegForm class first:

From Django Import forms# write a Class RegForm (forms) as required by the Django form component. Form):    user = forms. Charfield (label= ' username ')    pwd = forms. Charfield (label= ' password ')

Write a view function again:

# using the form component to implement the registration method def register2 (Request):    form_obj = RegForm ()    if Request.method = = ' POST ':        # When instantiating a Form object, Send the data submitted by post directly into        Form_obj = RegForm (Request. POST)        # Call the Form_obj checksum data method        if Form_obj.is_valid ():            return HttpResponse (' registered success ')    return render ( Request, ' register2.html ', {' Form_obj ': Form_obj})

Advanced View functions:

From Django Import formsfrom django.forms import widgetsfrom app01 import modelsfrom django.core.validators import Regexva Lidatorfrom django.core.exceptions Import validationerrorimport redef check_name (value): If ' Alex ' in Value:rai Se validationerror (' Not in line with socialist core Values ') # defines Formclass RegForm (forms. Form): User = forms. Charfield (label= ' username ', required=false, # Not allowed to be empty min_length=6, # Minimum length is 6 initial= ' wjs521 ', # The first value is wjs521 disabled=false, # can not edit validators=[check_name], error_messages={' min_length ' : ' Your length is too short, less than 6 ', ' Required ': ' Can't be Empty '} # pwd = forms. Charfield (label= ' password ', min_length=6, Widget=widgets. Passwordinput () # HTML plugin, the page displays the password is ciphertext) Re_pwd = forms. Charfield (label= ' Confirm password ', min_length=6, Widget=widgets. Passwordinput ()) # # gender = forms. Choicefield (# choices= (1, ' Male '), (2, ' Female '), (3, ' unknown ')), # Widget=widgets. CheCkboxselectmultiple () # can make multi-selection box #) # # hobby = forms. Choicefield (# # choices= (1, ' Football '), (2, ' Basketball '), (3, ' Color Ball ')), # Choices=models. Hobby.objects.all (). Values_list (' id ', ' name '), # widget=widgets. Selectmultiple () # can have multiple options #) phone = forms.    Charfield (label= ' mobile number ', # validators=[# regexvalidator (R ' ^1[3-9]\d{9}$ ', ' mobile phone number is not serious ') #] # def __init__ (self, *args, **kwargs): # Super (). __init__ (*args, **kwargs) # self.fields[' Hobby '].choi CES = models.    Hobby.objects.all (). Values_list (' id ', ' name ') # def clean_phone (self): # value = Self.cleaned_data.get (' phone ')  # if Re.match (R ' ^1[3-9]\d{9}$ ', value): # return value # # raise ValidationError (' mobile phone number is not serious ') #    def clean_re_pwd (self): # pwd = self.cleaned_data.get (' pwd ') # re_pwd = Self.cleaned_data.get (' re_pwd ') # # if pwd = = re_pwd: # return RE_PWD # Raise ValidationError (' two times password inconsistent ') def clean: pwd = self.cleaned_data.get (' pwd ') re_pwd = Self.cleaned_data.get (' re_pwd ') if PWD = = Re_pwd:return self.cleaned_data self.add_error (' re_pwd ', ' two times password inconsistent ') raise ValidationError ( ' Two times password inconsistent ')
From django.shortcuts import Render, Httpresponsefrom app01.forms import regformdef Register (Request):    Name_error = '    if Request.method = = ' POST ':        user = Request. Post.get (' user ')        pwd = Request. Post.get (' pwd ')        if Len (user) < 6:            Name_error = ' You are too short '        else:            # Data is eligible for the operation of the data            return HttpResponse (' registered success ')    return render (Request, ' register.html ', {"Name_error": Name_error}) def register2 (Request):    form_obj = RegForm ()    # Print (RegForm.hobby.choices)    # Print (11,form_obj.fields[' hobby '].choices)    if Request.method = = ' POST ':        form_obj = RegForm (Request. POST)        if Form_obj.is_valid ():            # Cleaned_data  is a verified data            print (form_obj.cleaned_data)            # Data Operation            return HttpResponse (' registered success ')    return render (Request, ' register2.html ', {"Form_obj": Form_obj})
Register2.html
<! DOCTYPE html>Characters commonly used segments and plugins

When creating a form class, it mainly involves "fields" and "plugins", which are used to validate the user's request data, and the plug-in is used to generate HTML automatically;

Initial

Initial value, the initial value inside the input box.

Class LoginForm (forms. Form):    username = forms. Charfield (        min_length=8,        label= ' username ',        initial= ' Wjs '  # Set default value    )    pwd = forms. Charfield (min_length=6, label= ' password ')
Error_messages

Rewrite the error message.

From Django Import Formsclass loginform (forms. Form):    username = forms. Charfield (        min_length=8,        label= ' username ',        error_messages={            ' required ': ' cannot be empty ',            ' invalid ': ' Format error ',            ' min_length ': ' User name minimum 8 bits '        }    '    pwd = forms. Charfield (min_length=6, label= ' password ')
Password
From Django Import Formsclass loginform (forms. Form):    pwd = forms. Charfield (        min_length=6,        label= ' password ',        widget=forms.widgets.passwordinput (attrs={' class ': ' C1 '},        Render_value=true        )    )
Radioselect

Single radio value is a string

From Django Import formsfrom django.forms import Widgetsclass loginform (forms. Form):    gender = Forms.fields.ChoiceField (        choices= (1, ' Male '), (2, ' Female '), (3, ' unknown ')),        label= ' sex '        , Initial=3,        widget=forms.widgets.radioselect ()    ) # single option
Radio Select
From django.forms Import Widgetsclass loginform (forms. Form):    hobby = Forms.fields.ChoiceField (        choices= (            1, ' basketball '),            (2, ' Football '),            (3, ' Color Ball ')        , ),        label= ' hobby ',        initial=3,        widget=forms.widgets.select ()    )

Multiple selection Select

Class LoginForm (forms. Form):    hobby = Forms.fields.MultipleChoiceField (        choices= (1, ' Basketball '), (2, ' Football '), (3, ' Color Ball ')),            label= ' hobbies ',            initial=[1,3],            widget=forms.widgets.selectmultiple ()    )
Radio checkbox
Class LoginForm (forms. Form):    keep = Forms.fields.ChoiceField (        label= ' Remember Password ',        initial= ' checked ',        widget= Forms.widgets.CheckboxInput ()    )
Multi-Select checkbox
Class LoginForm (forms. Form):    hobby = Forms.fields.MultipleChoiceField (        choices= (1, ' Basketball '), (2, ' Football '), (3, ' Color Ball ')),        label= ' hobby ',        initial=[1,3],        widget=forms.widgets.checkboxselectmultiple ()    )

Notes on choice:

When using a selection tag, be aware that the choices option is available from the data, but because the value obtained by the static field cannot be updated in real time, a custom construction method is required to achieve this.

Way One:

From django.forms import formfrom django.forms import widgetsfrom django.forms import Fieldsclass MyForm (Form):    user = fields. Choicefield (        # choices= (1, ' Shanghai '), (2, ' Beijing '),        initial=2,        widget=widgets. Select    )        # When manually adding data to the database in the background, the foreground cannot get the newly added data in time, and the server needs to be restarted, which is more troublesome. So by calling the parent class's __init__ () method-The new data is fetched when the page is refreshed.    def __init__ (self, *args, **kwargs):        super (Myform,self). __init__ (*args, **kwargs)        # self.fields[' user ' ].choices = ((1, ' Shanghai '), (2, ' Beijing '),        # or        self.fields[' user '].choices = models. Classes.objects.all (). Values_list (' id ', ' caption ')

Way two:

From Django Import formsfrom django.forms import fieldsfrom django.forms import models as Form_modelclass Finfo (forms. Form):    # Multi-select    authors = Form_model. Modelmutiplechoicefield (queryset=models. NNewType.objects.all ())    # Radio    # authors = Form_model. Modelchoicefield (queryset=models. NNewType.objects.all ())
Django form all built-in fields
Field Required=true, whether to allow null Widget=none, HTML plugin label=none, to generate LA         Bel label or display content Initial=none, initial value help_text= ", Help information (displayed next to the label) Error_messages=none, Error message {' Required ': ' cannot be null ', ' invalid ': ' Malformed '} validators=[], custom validation rule localize=false, whether Support for localized disabled=false, whether you can edit label_suffix=none label content suffix Charfield (Field) Max_length=non    E, maximum length min_length=none, minimum length strip=true whether to remove user input blank Integerfield (Field) Max_value=none, Max Min_value=none, Min. floatfield (Integerfield) ...             Decimalfield (Integerfield) Max_value=none, Max Min_value=none, Min Max_digits=none, Total length decimal_places=none, decimal length Basetemporalfield (Field) input_formats=none time formatting Datefi ELD (Basetemporalfield) format: 2015-09-01TIMEFIeld (Basetemporalfield) format: 11:12datetimefield (Basetemporalfield) format: 2015-09-01 11:12 Durationfield (Field) time between Spacer:%d%h:%m:%s.%f ...            Regexfield (Charfield) regex, self-customizing regular expression Max_length=none, maximum length min_length=none, Minimum length error_message=none, ignore, error message use error_messages={' invalid ': ' ... '} emailfield (Charfield) ...    Filefield (Field) allow_empty_file=false whether to allow empty files ImageField (Filefield) ... Note: Need PIL module, PIP3 install Pillow above two dictionary use, need to notice two points:-form form in enctype= "Multipart/form-data"-the view function in obj = M Yform (Request. POST, request.  FILES) Urlfield (Field) ... Booleanfield (Field) ... Nullbooleanfield (Booleanfield) ...             Choicefield (Field) ... choices= (), options, such as: Choices = ((0, ' Shanghai '), (1, ' Beijing '),) Required=true,    is required widget=none, plugin, default select plugin label=none, label content initial=none, initial value          Help_text= ',    Help tips Modelchoicefield (Choicefield) ... Django.forms.models.ModelChoiceField queryset, # Query the data in the database Empty_label= "---------", # Default empty display content To_field_name=none, # The value corresponding to the values in HTML field Li                        Mit_choices_to=none # Modelform in Queryset two filters Modelmultiplechoicefield (Modelchoicefield) ... Django.forms.models.ModelMultipleChoiceField Typedchoicefield (choicefield) coerce = Lambda Val:val to the selected value Make a conversion empty_value= the default value of "null" Multiplechoicefield (Choicefield) ... Typedmultiplechoicefield (multiplechoicefield) coerce = lambda Val:val one conversion for each selected value empty_value= ' Empty The default value of Combofield (Field) fields= () uses multiple validations, as follows: Verify the maximum length of 20, and verify the Mailbox format fields. Combofield (Fields=[fields. Charfield (max_length=20), fields. Emailfield (),]) Multivaluefield (Field) PS: Abstract class, subclasses can be implemented to aggregate multiple dictionaries to match a value, to mate with Multiwidget using Splitdatetimefield ( Multivaluefield) inPut_date_formats=none, List of formats: ['%y--%m--%d ', '%m%d/%y ', '%m/%d/%y '] input_time_formats=none format list: ['%h:%m:%s ', '%H:%M                :%s.%f ', '%h:%m '] Filepathfield (choicefield) file options, directory files displayed in page path, folder path Match=none, Regular match Recursive=false, recursive below folder Allow_files=true, allow file Allow_folders=false, allow text Clip required=true, Widget=none, Label=none, Initial=none, help_text= ' Genericipaddressfield protocol= ' bo Th ', Both,ipv4,ipv6 supported IP format unpack_ipv4=false parse IPv4 address, if:: ffff:192.0.2.1 time, can be resolved to 192.0.2.1, Ps:protoc OL must be both to enable Slugfield (Charfield) numbers, letters, underscores, minus (hyphens) ...   Uuidfield (Charfield) UUID type Django form built-in fields
Validation rules with self-check:
From django.forms import formfrom django.forms import widgetsfrom django.forms import Fieldsfrom django.core.validators i Mport regexvalidator# regexvalidator Regular Check Class MyForm (Form):    user = fields. Charfield (        validators=[regexvalidator (R ' ^[0-9]+$ ', ' Please enter Number '),             regexvalidator (R ' ^159[0-9]+$ ', ' number must start with 159 ' )],    )
Custom validation Rules:
Import refrom django.forms import formfrom django.forms import widgetsfrom django.forms import Fieldsfrom Django.core.exc Eptions Import validationerror# validationerror checksum error # Custom validation Rule def 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 (' mobile number Code format error ') class PublishForm (form): title = fields. Charfield (max_length=20, min_length=5, error_messages={' Required ': '                                            Title cannot be empty ', ' min_length ': ' title is at least 5 characters ', ' Max_length ': ' caption up to 20 characters '}, widget=widgets. TextInput (attrs={' class ': "Form-control", ' placeholder ': ' title 5-20 Characters '}) # Use a custom validation rule phone = fields. Charfield (Validators=[mobile_validate,], error_messages={' required ': ' Phone can'tis 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 ' mailbox format error '}, Widget=widgets. TextInput (attrs={' class ': "Form-control", ' placeholder ': U ' mailbox '}))
hook function 1. Local hooks
def clean_phone (self): value = Self.cleaned_data.get (' phone ') if Re.match (R ' ^1[3-9]\d{9}$ ', value): Return valueraise ValidationError (' Mobile phone number is not serious ')
2. Global Hooks
def clean (self):p WD = Self.cleaned_data.get (' pwd ') re_pwd = Self.cleaned_data.get (' re_pwd ') if pwd = = Re_pwd:return Self.cleaned_dataself.add_error (' re_pwd ', ' two times password inconsistent ') raise ValidationError (' two times password inconsistent ')

Django Form Forms

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.