Django form Forms

Source: Internet
Author: User

Form Introduction

When we previously submitted data in an HTML page using the form table one-way back end, we wrote some tags to get user input and wrapped them up with a form tag.

At the same time we need to check the user input in many scenarios, such as verifying whether the user input, the length and format of the input is not correct. If the user enters an error, they need to display the corresponding error message in the appropriate location on the page ...

The Django form component implements the functionality described above.

To summarize, 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
Normal mode handwriting registration function views.py
# Register DEF Register (Request):    error_msg = ""    if Request.method = = "POST":        username = Request. Post.get ("name")        pwd = Request. Post.get ("pwd")        # Check the registration information        if Len (username) < 6:            # User length is less than 6 bits            error_msg = "User name cannot be less than 6 bits"        else:            # Save username and password to database            return HttpResponse ("registration succeeded")    return render (Request, "register.html", {"error_msg": ERROR_MSG})
Login.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):    name = 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 Form_obj to verify the data        if Form_obj.is_valid ():            return HttpResponse ("registration succeeded")    return render ( Request, "register2.html", {"Form_obj": Form_obj})
Login2.html
<! DOCTYPE html>

Look at the Web page effect found also verified the function of the form:
? The front-end page is generated by the form class's object-generated HTML tags feature
? When the user name and password input is empty or the error is lost, the page prompts the user to submit the check function.
? When the user enters the wrong input again after the last content is also left in the input box and keep the last input

Form those things characters commonly used segment with plugin

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= "user name",        initial= "Zhang San"  # Set default value    )    pwd = forms. Charfield (min_length=6, label= "password")
Error_messages

Rewrite the error message.

Class LoginForm (forms. Form):    username = forms. Charfield (        min_length=8,        label= "user name",        initial= "Zhang San",        error_messages={            "required": "Cannot be empty",            "Invalid": "Malformed",            "min_length": "User name shortest 8 bits"        }    )    pwd = forms. Charfield (min_length=6, label= "password")
Password
Class 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

Class LoginForm (forms. Form):    username = forms. Charfield (        min_length=8,        label= "user name",        initial= "Zhang San",        error_messages={            "required": "Cannot be empty",            "Invalid": "Malformed",            "min_length": "User name shortest 8 bits"        }    )    pwd = forms. Charfield (min_length=6, label= "password")    gender = Forms.fields.ChoiceField (        (1, "Male"), (2, "female"), (3, "confidential") )),        label= "gender",        initial=3,        widget=forms.widgets.radioselect ()    )
Radio Select
Class LoginForm (forms. Form):    ...    Hobby = Forms.fields.ChoiceField (        choices= (1, "basketball"), (2, "Football"), (3, "Color Ball"),        label= "hobby",        initial=3,< C24/>widget=forms.widgets.select ()    )
Multiple selection Select
Class LoginForm (forms. Form):    ...    Hobby = Forms.fields.MultipleChoiceField (        choices= (1, "basketball"), (2, "Football"), (3, "Color Ball"),        label= "hobby"        , 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 the Selection tab, you need to be aware that the choices option is available from the database, but because a static field gets a value that cannot be updated in real time, you need to customize the construction method to do so.

Way One:

From django.forms import formfrom django.forms import widgetsfrom django.forms import fields Class MyForm (Form):     user = fields. Choicefield (        # choices= (1, ' Shanghai '), (2, ' Beijing '),        initial=2,        widget=widgets. Select    )     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_model class Finfo (forms. Form):    authors = Form_model. Modelmultiplechoicefield (queryset=models. NNewType.objects.all ())  # Multi-Select    # authors = Form_model. Modelchoicefield (queryset=models. NNewType.objects.all ())  # Single selection
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
Check

Way One:

From django.forms import formfrom django.forms import widgetsfrom django.forms import Fieldsfrom django.core.validators i Mport Regexvalidator class MyForm (Form):    user = fields. Charfield (        validators=[regexvalidator (R ' ^[0-9]+$ ', ' Please enter Number '), Regexvalidator (R ' ^159[0-9]+$ ', ' number must start with 159 ')],    )

Way two:

Import refrom django.forms import formfrom django.forms import widgetsfrom django.forms import Fieldsfrom Django.core.exc Eptions Import ValidationError # Custom validation Rule def mobile_validate (value): Mobile_re = Re.compile (R ' ^ (13[0-9]|15[012356789]|1 7[678]|18[0-9]|14[57]) [0-9]{8}$ ') if not Mobile_re.match (value): Raise ValidationError (' mobile phone number format error ') class Publis Hform (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 ': ' The phone cannot 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 ' mailbox format error '}, Widget=widgets. TextInput (attrs={' class ': "Form-control", ' placeholder ': U ' mailbox '}))
Supplemental Advanced Application Bootstrap style
<! DOCTYPE html>Add Styles in bulk

This can be done by overriding the Init method of the form class.

Class LoginForm (forms. Form):    username = forms. Charfield (        min_length=8,        label= "user name",        initial= "Zhang San",        error_messages={            "required": "Cannot be empty",            "Invalid": "Malformed",            "min_length": "User name min    .    8 bits"} ... def __init__ (self, *args, **kwargs):        super ("LoginForm, Self"). __init__ (*args, **kwargs) for        field in ITER ( Self.fields):            self.fields[field].widget.attrs.update ({                ' class ': ' Form-control '            })

Modelform

The ultimate combination of form and model.

Class Bookform (forms. Modelform):    class Meta:        model = models.        book fields = "__all__"        labels = {            "title": "Titles",            "price": "Prices"        }        widgets = {            "password": Forms.widgets.PasswordInput (attrs={"class": "C1"}),        }

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.