forms components in Django detail example

  • 2021-01-25 07:47:52
  • OfStack

Form introduction

When we used the form form on the HTML page to submit data to the back end, we wrote some tags that took user input and wrapped them with form tags.

At the same time, we need to check the user's input in many scenarios, such as checking whether the user input, the length and format of the input is correct. If there is an error in the user's input content, it is necessary to display the corresponding error information in the corresponding position on the page.

The Django component implements the functionality described above.

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

Generate the HTML tags available for the page Verify the data submitted by the user Keep the last input

my_forms.py First define an UserForm class in the application directory my_forms.py


from django import forms
 from django.forms import widgets 
   class UserForm(forms.Form):
     username = forms.CharField(min_length=4, label=' The user name ',
                   widget=widgets.TextInput(attrs={"class": "form-control"}),
                   error_messages={
                     "required": " The user name cannot be empty ",
                   })
     pwd = forms.CharField(min_length=4, label=' password ',
                error_messages={
                  "required": " The password cannot be empty ",
                },
                widget=widgets.PasswordInput(attrs={"class": "form-control"}))
     r_pwd = forms.CharField(min_length=4, label=' Confirm password ',
                 widget=widgets.PasswordInput(attrs={"class": "form-control"}),
                 error_messages={
                   "required": " The password cannot be empty ",
                 })
     email = forms.EmailField(label=' email ',
                 widget=widgets.EmailInput(attrs={"class": "form-control"}),
                 error_messages={
                   "required": ' Mailboxes cannot be empty ',
                   "invalid": " Email format error ",
                 })
     tel = forms.CharField(label=' Mobile phone no. ',
                widget=widgets.TextInput(attrs={"class": "form-control"}),
                )

Write another view function:

I'm writing a view function


   def reg(request):
     form = UserForm()
     if request.method == "POST":
       print(request.POST)
       #  instantiation form Object when put post The submitted data goes straight in 
       form = UserForm(request.POST) # form The form of name The property value should be the same as forms The field name of the component 1 to 
       if form.is_valid():
         print(form.cleaned_data)
         return HttpResponse(' Registered successfully ')
     return render(request, 'reg.html', locals())

login.html


  <!DOCTYPE html>
   <html lang="zh_CN">
   <head>
     <meta charset="UTF-8">
     <meta http-equiv="x-ua-compatible" content="IE=edge">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <title> registered </title>
   </head>
   <body>
   <h3> traditional form The form </h3>
   <form action="" method="post">
     {% csrf_token %}
     <p> User name: <input type="text" name="username"></p>
     <p> Password: <input type="password" name="pwd"></p>
     <p> Confirm password: <input type="password" name="r_pwd"></p>
     <p> Email address: <input type="email" name="email"></p>
     <p> Mobile phone no. : <input type="tel" name="tel"></p>
     <p><input type="submit" value=" submit "></p>
   </form>
   <h3>forms Component Render 1</h3>
   <form action="" method="post" novalidate>
     {% csrf_token %}
     <p>{{ form.username.label }} : {{ form.username }} <span>{{ form.username.errors.0 }}</span></p>
     <p> Password: {{ form.pwd }}
       <span>{{ form.pwd.errors.0 }}</span></p>
     <p> Confirm password: {{ form.r_pwd }}
       <span>{{ form.r_pwd.errors.0 }}</span></p>
     <p> Email address: {{ form.email }}
       <span>{{ form.email.errors.0 }}</span></p>
     <p> Mobile phone no. : {{ form.tel }}
       <span>{{ form.tel.errors.0 }}</span></p>
     <p><input type="submit" value=" submit "></p>
   </form>
   <h3>forms Component rendering labels 2</h3>
     <form action="" method="post" novalidate>
       {% csrf_token %}
       {% for field in form %}
         <div class="form-group clearfix">
           <label for="">{{ field.label }}</label>
           {{ field }}
           <span style="color: red" class="pull-right">{{ field.errors.0 }}</span>
           {% if field.name == 'r_pwd' %}
             <span style="color: red" class="pull-right">{{ errors.0 }}</span>
           {% endif %}
         </div>
       {% endfor %}
       <input type="submit" value=" registered " class="btn btn-default pull-right">
     </form>
   <h3>forms Component rendering labels 3   Not recommended </h3>
   <form action="" method="post">
     {% csrf_token %}
     {{ form.as_p }}
     <input type="submit" value=" registered ">
   </form>
   </body>
   </html>

The results of the web page also verify the function of ES37en:

The & # 8226; The front-end page is generated by an object of class form > Generate HTML tag functionality

The & # 8226; When the user name and password are entered blank or incorrectly, the page will prompt -- > User submission verification function

The & # 8226; When the user makes a typo and reenters the previous content, it will remain in the input box > Keep the last input

Form stuff

Commonly used fields and plug-ins

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

initial

Initial value, the initial value in the input box.


class LoginForm(forms.Form):
  username = forms.CharField(
    min_length=8,
    label=" The user name ",
    initial=" zhang 3" #  Set Default Values 
  )
  pwd = forms.CharField(min_length=6, label=" password ")

error_messages

Overwrite the error message.


class LoginForm(forms.Form):
  username = forms.CharField(
    min_length=8,
    label=" The user name ",
    initial=" zhang 3",
    error_messages={
      "required": " Can't be empty ",
      "invalid": " Invalid format ",
      "min_length": " Shortest User Name 8 position "
    }
  )
  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

A single radio value is a string


class LoginForm(forms.Form):
  username = forms.CharField(
    min_length=8,
    label=" The user name ",
    initial=" zhang 3",
    error_messages={
      "required": " Can't be empty ",
      "invalid": " Invalid format ",
      "min_length": " Shortest User Name 8 position "
    }
  )
  pwd = forms.CharField(min_length=6, label=" password ")
  gender = forms.fields.ChoiceField(
    choices=((1, " male "), (2, " female "), (3, " A secret ")),
    label=" gender ",
    initial=3,
    widget=forms.widgets.RadioSelect()
  )

Radio Select


class LoginForm(forms.Form):
  ...
  hobby = forms.fields.ChoiceField(
    choices=((1, " basketball "), (2, " football "), (3, " The double chromosphere "), ),
    label=" hobby ",
    initial=3,
    widget=forms.widgets.Select()
  )

Multi-select Select


class LoginForm(forms.Form):
  ...
  hobby = forms.fields.MultipleChoiceField(
    choices=((1, " basketball "), (2, " football "), (3, " The double chromosphere "), ),
    label=" hobby ",
    initial=[1, 3],
    widget=forms.widgets.SelectMultiple()
  )

Radio checkbox


class LoginForm(forms.Form):
  ...
  keep = forms.fields.ChoiceField(
    label=" Whether to remember the password ",
    initial="checked",
    widget=forms.widgets.CheckboxInput()
  )

Multi-select checkbox


   def reg(request):
     form = UserForm()
     if request.method == "POST":
       print(request.POST)
       #  instantiation form Object when put post The submitted data goes straight in 
       form = UserForm(request.POST) # form The form of name The property value should be the same as forms The field name of the component 1 to 
       if form.is_valid():
         print(form.cleaned_data)
         return HttpResponse(' Registered successfully ')
     return render(request, 'reg.html', locals())
0

Notes for choice:

When using the select tag, note that the options for choices can be obtained from the database, but since values obtained from static fields *** cannot be updated in real time ***, custom constructors are required to do this.

Method 1:


   def reg(request):
     form = UserForm()
     if request.method == "POST":
       print(request.POST)
       #  instantiation form Object when put post The submitted data goes straight in 
       form = UserForm(request.POST) # form The form of name The property value should be the same as forms The field name of the component 1 to 
       if form.is_valid():
         print(form.cleaned_data)
         return HttpResponse(' Registered successfully ')
     return render(request, 'reg.html', locals())
1

Method 2:


   def reg(request):
     form = UserForm()
     if request.method == "POST":
       print(request.POST)
       #  instantiation form Object when put post The submitted data goes straight in 
       form = UserForm(request.POST) # form The form of name The property value should be the same as forms The field name of the component 1 to 
       if form.is_valid():
         print(form.cleaned_data)
         return HttpResponse(' Registered successfully ')
     return render(request, 'reg.html', locals())
2


Django Form built-in fields

check

Method 1:


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]+$', ' The number must be 159 At the beginning ')],
  )

Method 2:


   def reg(request):
     form = UserForm()
     if request.method == "POST":
       print(request.POST)
       #  instantiation form Object when put post The submitted data goes straight in 
       form = UserForm(request.POST) # form The form of name The property value should be the same as forms The field name of the component 1 to 
       if form.is_valid():
         print(form.cleaned_data)
         return HttpResponse(' Registered successfully ')
     return render(request, 'reg.html', locals())
4

Method 3:


   def reg(request):
     form = UserForm()
     if request.method == "POST":
       print(request.POST)
       #  instantiation form Object when put post The submitted data goes straight in 
       form = UserForm(request.POST) # form The form of name The property value should be the same as forms The field name of the component 1 to 
       if form.is_valid():
         print(form.cleaned_data)
         return HttpResponse(' Registered successfully ')
     return render(request, 'reg.html', locals())
5

Conclusion:


   def reg(request):
     form = UserForm()
     if request.method == "POST":
       print(request.POST)
       #  instantiation form Object when put post The submitted data goes straight in 
       form = UserForm(request.POST) # form The form of name The property value should be the same as forms The field name of the component 1 to 
       if form.is_valid():
         print(form.cleaned_data)
         return HttpResponse(' Registered successfully ')
     return render(request, 'reg.html', locals())
6

conclusion


Related articles: