Use the form form djano

First, use instructions

  1. Create a forms.py file, specify the app on them, and then write the form on the inside.

  2. The form is achieved by the class inherits from forms.Form, then define the fields to be verified inside.

  3. In the form, create a field with the model is exactly the same, but there is no null = True or blank = True and so these types of parameters, some parameters are required = True / False.

  4. Use is_valid () method can verify whether the data submitted by the user legitimate, and name HTML form element and must be in the form of name django consistent, otherwise not match.

  5. is_bound Attributes: form used to indicate whether or not data bound, if bound, it returns True, otherwise False.

  6. cleaned_data: This is is_valid () returns True when the data submitted by the user to save up.

 

Second, the Form Description

Sample code:

from django import forms


class LoginForm(forms.Form):
    username = forms.CharField(max_length=16, min_length=8, strip=True, error_messages={
        "Max_length": "user name length over 16"
        "Min_length": "User name length is less than 8",
        "Required": "Username can not be empty."
    })

    password = forms.CharField(strip=True, error_messages={
        "Required": "Password can not be empty."
    })

Field style module forms:

__all__ = (
    'Field', 'CharField', 'IntegerField',
    'DateField', 'TimeField', 'DateTimeField', 'DurationField',
    'RegexField', 'EmailField', 'FileField', 'ImageField', 'URLField',
    'BooleanField', 'NullBooleanField', 'ChoiceField', 'MultipleChoiceField',
    'ComboField', 'MultiValueField', 'FloatField', 'DecimalField',
    'SplitDateTimeField', 'GenericIPAddressField', 'FilePathField',
    'SlugField', 'TypedChoiceField', 'TypedMultipleChoiceField', 'UUIDField',
)

field parameter forms the module for verification:

 

Field
        required = True # request can not empty 
        the widget = None # the HTML widget 
        label = None # for generating a display content lable or tag 
        Initial = None # initial value 
        help_text = '' # help information (shown next to the label) 
        error_messages, = None # ( error message { 'required': 'not empty', 'invalid': 'malformed'}) 
        show_hidden_initial = False # whether the current plus a hidden behind the plug and the plug has a default value (whether the input can be used to verify two agreement) 
        validators = () # custom validation rules 
        localize = False # supports localization 
        Disabled = False # can edit 
        label_suffix = None #label content suffix

        CharField(Field)
    MAX_LENGTH = None, the maximum length of
    min_length = None, minimum length
    Strip = Are True removing user input blank

IntegerField(Field)
    MAX_VALUE = None, maximum
    MIN_VALUE = None, minimum

FloatField(IntegerField)
    ...

DecimalField(IntegerField)
    MAX_VALUE = None, maximum
    MIN_VALUE = None, minimum
    max_digits = None, total length
    decimal_places = None, fractional bit length

BaseTemporalField(Field)
    input_formats = None Time Format   

DateField (BaseTemporalField) Format: 2015-09-01 
TimeField (BaseTemporalField) format: 11:12 
DateTimeField (BaseTemporalField) Format: 2015-09-01 11:12

DurationField (Field) Interval: % D% H:% M:%% S. F
    ...

RegexField(CharField)
    regex, custom regular expression
    MAX_LENGTH = None, the maximum length of
    min_length = None, minimum length
    ERROR_MESSAGE = None, ignore the error message used = {error_messages, ' invalid ' : ' ... ' }

EmailField(CharField)      
    ...

FileField(Field)
    allow_empty_file = False whether to allow empty file

ImageField(FileField)      
    ...
    Note: You need PIL module, pip3 install Pillow
    If two or more dictionaries, you should consider two things:
        - form = form the enctype " multipart / form-Data " 
        - View function = obj the MyForm (of request.POST, request.FILES)

URLField(Field)
    ...

BooleanField(Field)  
    ...

NullBooleanField(BooleanField)
    ...

ChoiceField(Field)
    ...
    choices = (), options such as: choices = ((0, ' Shanghai ' ), (1, ' Beijing ' ),)
    required = True, Required
    the widget = None, plug-in, select the default plug-ins
    label = None, the contents of the Label
    Initial = None, the initial value
    help_text = '' , Helpful Hints

ModelChoiceField(ChoiceField)
    ...                        django.forms.models.ModelChoiceField
    queryset,                   # data query database 
    empty_label = " --------- " ,    # default empty display content 
    to_field_name = None,         # field value corresponding to the value of the HTML 
    limit_choices_to = None       # ModelForm of the secondary queryset filter

ModelMultipleChoiceField(ModelChoiceField)
    ...                        django.forms.models.ModelMultipleChoiceField

TypedChoiceField(ChoiceField)
    coerce = the lambda Val: Val values for the selected one conversion
    empty_value = ''             default null values

MultipleChoiceField(ChoiceField)
    ...

TypedMultipleChoiceField(MultipleChoiceField)
    coerce = the lambda Val: Val for each value is selected in a conversion
    empty_value = ''             default null values

ComboField(Field)
    Fields = () using a plurality of verification, as follows: i.e., the maximum length of 20 validation, verification and mailbox format
                               fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),])

MultiValueField(Field)
    PS: abstract class, subclass, the polymerization can be implemented to match a value of a plurality of dictionaries to use with MultiWidget

SplitDateTimeField(MultiValueField)
    input_date_formats = None, list format: [ ' % the Y -% m -% D ' , ' % D% m /% the Y ' , ' % m /% D /% Y ' ]
    input_time_formats = None list format: [ ' % H:% M:% S ' , ' % H:% M:% S. F% ' , ' % H:% M ' ]

FilePathField (ChoiceField) file option, directory files are displayed in the page
    path, folder path
    match = None, matching canonical
    recursive This = False, the following folders recursively
    allow_files = True, allow file
    allow_folders = False, allows folder
    required=True,
    widget=None,
    label=None,
    initial=None,
    help_text=''

GenericIPAddressField
    Protocol = ' both ' , both, IPv4, IPv6 supports IP format
    unpack_ipv4 = False resolve ipv4 address, if it is :: ffff: 192.0.2.1 when resolves to 192.0.2.1 , PS: Protocol must be enabled in order to both

SlugField (CharField) numbers, letters, underscores, minus (hyphen)
    ...

UUIDField(CharField)           uuid类型
    ...

 

Custom error message:

  There are parameters in a error_messages field parameter whose value is a dictionary, field validation key represents the name does not comply, the value represents a custom error messages

 

from django import forms


class LoginForm(forms.Form):
    username = forms.CharField (= 16 MAX_LENGTH, min_length =. 8, Strip = True, error_messages, = {
         " MAX_LENGTH " : " User name length over 16 " ,
         " min_length " : " User name length is less than 8 " ,
         " required " : " user name can not be empty ."
    })

    password = forms.CharField (Strip = True, error_messages, = {
         " required " : " empty entry is not " 
    })

 

Third, use the form

  Note: Although the form can be generated front page, but the actual function with less, mainly with form form validation.

 

from .forms import RegisterFrom
from .models import User
def register(request):
    if request.method == 'GET':
        form = RegisterFrom()
        return render(request,'ts22/register.html',
                      context={'form':form})
    elif request.method == 'POST':
        form = RegisterFrom(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            password_repeat = form.cleaned_data.get('password_repeat')
            email = form.cleaned_data.get('email')
            if password == password_repeat:
                the User = User.objects.create (username = username, password = password, Email = Email)
                 return HttpResponse ( ' registered successfully! ' )
             the else :
                 return HttpResponse ( ' registration failed! ' )
         the else :
             return HttpResponse ( ' Registration Failed! ' )
# Create your views here.
class LoginView(views.View):
    def get(self, request):
        return render(self.request, 'user/login.html')

    DEF POST (Self, Request):
         # parameters submitted pass into the form, for each comparison verification 
        form = the LoginForm (of request.POST)
         Print (of request.POST)
         Print (form)
         # Form verified by 
        IF form.is_valid ():
            username = form.cleaned_data.get("username")
            password = form.changed_data.get("password")
            user_info = User.objects.filter (username = username) .first ()
             IF user_info.get ( " username " , None) and (user_info.get ( " password " ) == password):
                 return HttpResponse ( " successful landing! " )
             the else :
                 return HttpResponse ( " ! username does not exist " )
         # form validation fails, the failure to obtain information for processing 
        the else :
             # <tr><th><label for="id_username">Username:</label></th><td><ul class="errorlist"><li>用户名长度小于8位</li></ul><input type="text" name="username" value="admin" maxlength="16" minlength="8" required id="id_username"></td></tr>
            # <tr><th><label for="id_password">Password:</label></th><td><input type="text" name="password" value="asd2743075" required id="id_password"></td></tr>
            # <ul class="errorlist"><li>username<ul class="errorlist"><li>用户名长度小于8位</li></ul></li></ul>
            { "username": [{ "Message": "\ u7528 \ u6237 \ u540d \#(form.errors.as_data ())
            Print{ 'username': [the ValidationError ([ 'username length of less than 8'])]}#(form.errors)
            Print
            
            print(form.errors.as_json())
            return HttpResponse(form.errors.as_json())

Fourth, Reference: https://www.liujiangblog.com/course/django/153

Guess you like

Origin www.cnblogs.com/loveprogramme/p/12457254.html