from

Form Introduction 

When submitting data to the back end before we use a form in an HTML page form, will write the label to obtain user input and label them with a form wrap.

At the same time we all need to do in a lot of scenes of user input validation, such as checking whether the user input, the input length and format is not correct. If the user input has an error requires appropriate error message corresponding to the location on the page ..

Django form component to achieve the functions described above.

To sum up, in fact, the main function of form components as follows:

  • HTML tags generated pages available
  • To verify the data submitted by users
  • Keep last Input content

Registered ordinary handwriting function

views.py

# Sign 
DEF the Register (Request):
    error_msg = ""
    if request.method == "POST":
        username = request.POST.get("name")
        pwd = request.POST.get ( " pwd " )
         # registration information validator 
        IF len (username) <. 6 :
             # User length of less than 6 
            ERROR_MSG = " User name length can not be less than 6 " 
        the else :
             # username and password to the database 
            return the HttpResponse ( " registration is successful " )
     return the render (Request, " register.html " , { " ERROR_MSG " : ERROR_MSG})

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <Title> Registration Page </ title>
</head>
<body>
<form action="/reg/" method="post">
    {% csrf_token %}
    <p>
        username:
        <input type="text" name="name">
    </p>
    <p>
        password:
        <input type="password" name="pwd">
    </p>
    <p>
        <input type="submit" value="注册">
        <p style="color: red">{{ error_msg }}</p>
    </p>
</form>
</body>
</html>

Use form components to achieve registration function

views.py

Define a good RegForm categories:

from django import forms

# Accordance with the requirements Django form assembly to write a class 
class regform (forms.Form):
    name = forms.CharField (label = " username " )
    pwd = forms.CharField (label = " password " )

In trying to write a function:

# Use form components to achieve the registration mode 
DEF REGISTER2 (Request):
    form_obj = regform ()
     IF request.method == " the POST " :
         # instantiated form of an object when the post data submitted directly pass over into 
        form_obj = regform (of request.POST)
         # method calls form_obj check data 
        IF form_obj .is_valid ():
             return the HttpResponse ( " registration is successful " )
     return the render (Request, " register2.html " , { " form_obj " : form_obj})

login2.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <Title> Register 2 </ title>
</head>
<body>
    <form action="/reg2/" method="post" novalidate autocomplete="off">
        {% csrf_token %}
        <div>
            <label for="{{ form_obj.name.id_for_label }}">{{ form_obj.name.label }}</label>
            {{ form_obj.name }} {{ form_obj.name.errors.0 }}
        </div>
        <div>
            <label for="{{ form_obj.pwd.id_for_label }}">{{ form_obj.pwd.label }}</label>
            {{ form_obj.pwd }} {{ form_obj.pwd.errors.0 }}
        </div>
        <div>
            <input type="submit" class="btn btn-success" value="注册">
        </div>
    </form>
</body>
</html>

See page effects are also found in the form of validation functions:
• the front page is the object form generated classes -> Generate HTML tags function
• When the user name and password for the page will be prompted after empty or wrong -> check user submitted function
• after the user inputs the wrong again when the last content also remains in the input box -> Keep last input content

Form those things

Common Fields with plug-ins

When creating Form class, mainly related to the field of [] and [] plug, field is used to authenticate the user requesting the data, for automatically generating the HTML plug;

initial

The initial value, the initial value input box inside.

class LoginForm(forms.Form):
    username = forms.CharField(
        min_length=8,
        label = " username " ,
        Initial = " John Doe "   # Set the default value 
    )
    pwd = forms.CharField(min_length=6, label="密码")

error_messages

Rewrite error message.

class LoginForm(forms.Form):
    username = forms.CharField(
        min_length=8,
        label = " username " ,
        Initial = " John Doe " ,
        error_messages, = {
             " required " : " not empty " ,
             " invalid " : " Format Error " ,
             " min_length " : " User name shortest 8 "
        }
    )
    pwd = forms.CharField(min_length=6, label="密码")

password

class LoginForm(forms.Form):
    ...
    pwd = forms.CharField(
        min_length=6,
        label = " password " ,
        widget=forms.widgets.PasswordInput(attrs={'class': 'c1'}, render_value=True)
    )

radioSelect

Value is a string of single radio

class LoginForm(forms.Form):
    username = forms.CharField(
        min_length=8,
        label = " username " ,
        Initial = " John Doe " ,
        error_messages, = {
             " required " : " not empty " ,
             " invalid " : " Format Error " ,
             " min_length " : " User name shortest 8 "
        }
    )
    pwd = forms.CharField(min_length=6, label="密码")
    gender = forms.fields.ChoiceField(
        choices = ((. 1, " M " ), (2, " F " ), (3, " Confidential " )),
        label = " sex " ,
        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,
        widget=forms.widgets.Select()
    )

Multiple choice 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

Copy the code
class LoginForm(forms.Form):
    ...
    keep = forms.fields.ChoiceField(
        label = "whether Remember Password"
        initial="checked",
        widget=forms.widgets.CheckboxInput()
    )
Copy the code

Multi-select checkbox

Copy the code
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()
    )
Copy the code

Notes about the choice:

When using the select tag, you need to pay attention to choices of options can be obtained from the database, but because it is the value of the static field can not be updated *** *** get real-time, you need to customize the configuration method to achieve this purpose.

method one:

Copy the code
from django.forms import Form
from django.forms import widgets
from 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')
Copy the code

Second way:

Copy the code
from django import forms
from django.forms import fields
from django.forms import models as form_model

 
class FInfo(forms.Form):
    authors = form_model.ModelMultipleChoiceField(queryset=models.NNewType.objects.all())  # 多选
    # authors = form_model.ModelChoiceField(queryset=models.NNewType.objects.all())  # 单选
Copy the code

Django Form All built-in fields

  Django Form built-in fields

check

method one:

Copy the code
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 the number'), RegexValidator (r '^ 159 [0-9] + $', 'number must start 159')],
    )
Copy the code

Second way:

Copy the code
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[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(Form):
 
 
    title = fields.CharField(max_length=20,
                            min_length=5,
                            error_messages = { 'required': 'title can not be empty',
                                            'Min_length': 'a minimum of five title character'
                                            'Max_length': 'title up to 20 characters'},
                            widget=widgets.TextInput(attrs={'class': "form-control",
                                                          'Placeholder': 'title 5-20 characters'}))
 
 
    # Use a custom validation rules
    phone = fields.CharField(validators=[mobile_validate, ],
                            error_messages = { 'required': 'phone can not be empty'},
                            widget=widgets.TextInput(attrs={'class': "form-control",
                                                          'Placeholder': u 'phone number'}))
 
    email = fields.EmailField(required=False,
                            error_messages = { 'required': u 'mailbox can not be empty', 'invalid': u 'mailbox format error'},
                            widget=widgets.TextInput(attrs={'class': "form-control", 'placeholder': u'邮箱'}))
Copy the code

Advanced Supplementary

Application of Bootstrap styles

  Django form Bootstrap style simple example application

Bulk add style

It may be achieved by rewriting form class init method.

  Bulk add style

model Form

The ultimate combination of form and model.

Copy the code
class BookForm(forms.ModelForm):

    class Meta:
        model = models.Book
        fields = "__all__"
        labels = {
            "title": "书名",
            "price": "价格"
        }
        widgets = {
            "password": forms.widgets.PasswordInput(attrs={"class": "c1"}),
        }
Copy the code

 class Meta: the Common Parameters:

Copy the code
model = models.Student # corresponding class in the Model
fields = "__all__" # field, if it is __all__, is to represent all the fields listed
None # exclude = Fields excluded
labels = None # prompt
help_texts = None # Help tips
widgets = None # custom plug-in
error_messages = None # custom error messages
Copy the code

Guess you like

Origin www.cnblogs.com/yzl666/p/11012871.html