Django Form Form validation and verification fields

Summary

Filtering of the data submitted by the user, to verify, to avoid illegal data submitted, suggesting that the format of the data entered by the user. These are a function we must achieve in the page. For example, we can use to write their own regular expressions to validate this method is a relatively often thought, for example, some common being the great God who collected online expression set: original Mengchuo

Django-Form


premise

But in Django, we have the most simple and practical quick way to achieve this.
We have a simple sign-up page to get started:

# urls.py
url(r'^register/', views.Register.as_view(),name='register'),
# views.py
class Register(View):
    def get(self, request):
        return render(request, 'register.html',)

    def post(self, request):
        return HttpResponse("OK")
# register.html
<form action="{% url 'register' %}" method="post">
    {% csrf_token %}
        <p><input type="text" name="user"></p>
        <p><input type="text" name="password"></p>
        <p><input type="text" name="email"></p>
        <p><input type="submit" name="提交"></p>
</form>

In this context, we need to do to limit a user-entered data, what needs to be done to limit it, we probably simple example:

  • Username: length greater than 6 is less than 24, there can be special characters, alphanumeric only underscores not be empty
  • Password: length greater than 6 is less than 32, can not be empty
  • E-mail: meet mailbox format, can not be empty

To achieve the above requirements

# views.py

class FormVerify(forms.Form):
    username = fields.CharField(max_length=24,
                                min_length=6,
                                error_messages={
                                    "required": "用户名不能为空",
                                    'min_length': "长度小于6",
                                    'max_length': "长度大于32",
                                })
    email = fields.EmailField(
        error_messages={
            'required': "邮箱不能为空",
            "invalid": "邮箱格式错误",
        }
    )
    password = fields.CharField(
        max_length=32,
        min_length=6,
        error_messages={
            'required': "密码不能为空",
            'min_length': "密码长度不能小于6",
            'max_length': "密码长度不能大于32"
        },
        widget=widgets.PasswordInput()
    )




class Register(View):
    def get(self, request):
        return render(request, 'register.html',)

    def post(self, request):
        return HttpResponse("OK")

Step Description:

  1. A custom class needs to inherit forms.Form
  2. Class field name and the form must be submitted the data nameis consistent, the use of fieldsvarious types of fields
  3. And then specify the various constraints they want on the field

Django built-in fields in finishing

Official Documents

Field base class
required                     是否可以为空
label                        等同于html中label,input框前面显示的内容
label_suffix                 lable显示内容与input之间的分隔符,例如冒号:
initial                      初始值
widget                       自定制生成html的标签
help_text                    input框显示的提示内容
error_messages               定制各种错误信息
validators=[]                自定制匹配规则
localize                     本地化,一般会在时间上使用
disabled                     可以将input设置成不可编辑状态
has_changed()                监测字段内容是否改变
show_hidden_initial=False,   是否在当前插件后面再加一个隐藏的且具有默认值的插件(可用于检验两次输入是否一直)
CharField(Field)

Text Types

Default widget: TextInput
max_length
min_length
strip=True    去掉输入中的空格
empty_value    空值的默认值
IntegerField(Field)

Integer type

max_value
min_value
FloatField(IntegerField)

Floating-point type

Default widget: NumberInput
Error message keys: required, invalid, max_value, min_value
DecimalField(IntegerField)

Decimal type

Default widget: NumberInput when Field.localize is False, else TextInput.
Error message keys: required, invalid, max_value, min_value, max_digits, max_decimal_places, max_whole_digits

max_value  最大值
min_value  最小值
max_digits  总长度
decimal_places  小数长度
ChoiceField(Field)

Radio type

Default widget: Select
Error message keys: required, invalid_choice
MultipleChoiceField(ChoiceField)

Multiple choice type

Default widget: SelectMultiple
Error message keys: required, invalid_choice, invalid_list
TypedMultipleChoiceField(MultipleChoiceField)

With MultipleChoiceField, but accepts additional parameters coerceandempty_value

Default widget: SelectMultiple
Error message keys: required, invalid_choice
GenericIPAddressField(CharField)

IP addresses

Default widget: TextInput
Error message keys: required, invalid
protocol   支持的IP地址类型: both (default), IPv4 or IPv6
unpack_ipv4   解析为ipv4地址,可以将::ffff:192.0.2.1解析为192.0.2.1
TypedChoiceField(ChoiceField)

With ChoiceField, but accepts additional parameters coerceandempty_value

Default widget: Select
Error message keys: required, invalid_choice
coerce         接收一个参数并返回强制转换后的值的一个函数
empty_value    空值的默认值
TimeField(BaseTemporalField)

Time Format Type, datetime.timeObject

Default widget: TextInput
Error message keys: required, invalid
input_formats  如果未指定,默认类型:
         '%H:%M:%S',     # '14:30:59'
         '%H:%M',        # '14:30'
DateField(BaseTemporalField)

Date format type datetime.dateObject

Default widget: DateInput
Error message keys: required, invalid
input_formats: 默认格式(default):
        ['%Y-%m-%d',      # '2006-10-25'
         '%m/%d/%Y',      # '10/25/2006'
         '%m/%d/%y']      # '10/25/06'
但是在seettings中设置 USE_L10N=False,以下的格式也将包含在默认的输入格式中
         ['%b %d %Y',      # 'Oct 25 2006'
          '%b %d, %Y',     # 'Oct 25, 2006'
          '%d %b %Y',      # '25 Oct 2006'
          '%d %b, %Y',     # '25 Oct, 2006'
          '%B %d %Y',      # 'October 25 2006'
          '%B %d, %Y',     # 'October 25, 2006'
          '%d %B %Y',      # '25 October 2006'
          '%d %B, %Y']     # '25 October, 2006'
DateTimeField(BaseTemporalField)

The date and time format type, datetime.datetimeobjects

Default widget: DateTimeInput
Error message keys: required, invalid
input_formats   默认格式:
          ['%Y-%m-%d %H:%M:%S',    # '2006-10-25 14:30:59'
           '%Y-%m-%d %H:%M',       # '2006-10-25 14:30'
           '%Y-%m-%d',             # '2006-10-25'
           '%m/%d/%Y %H:%M:%S',    # '10/25/2006 14:30:59'
           '%m/%d/%Y %H:%M',       # '10/25/2006 14:30'
           '%m/%d/%Y',             # '10/25/2006'
           '%m/%d/%y %H:%M:%S',    # '10/25/06 14:30:59'
           '%m/%d/%y %H:%M',       # '10/25/06 14:30'
           '%m/%d/%y']             # '10/25/06'
  • It will be opened from the 1.7 version, useSplitDateTimeWidget
EmailField(CharField)

Mail type

Default widget: EmailInput
Error message keys: required, invalid
URLField(CharField)

URL type

Default widget: URLInput
Error message keys: required, invalid
max_length
min_length
SlugField(CharField)

Numbers, letters, underscores, minus

Default widget: TextInput
Error messages: required, invalid
allow_unicode 
FileField(Field)

Files, one UploadedFileobject, you can use this object in the rear end to get chunksa method to save the file

Default widget: ClearableFileInput
Error message keys: required, invalid, missing, empty, max_length
max_length 文件最大长度
allow_empty_file 是否允许文件为空
FilePathField(ChoiceField)

File path, Unicode objects

Default widget: Select
Error message keys: required, invalid_choice
path 路径
recursive          Default is False 是否递归
match              自定义正则匹配,匹配这个表达式的名称才允许作为选项
allow_files        Default is True   是否包含文件
allow_folders      Default is False  是否包含文件夹
ImageField(FileField)

ImageField need to use Pillow and use a supported image format, the UploadedFile object will have an extra attribute image, the image comprising Pillow example, to check for a valid image file, and is:
form form: enctype="multipart/form-data
views function:obj = MyForm(request.POST, request.FILES)

Default widget: ClearableFileInput
Error message keys: required, invalid, missing, empty, invalid_image
RegexField(CharField)
Default widget: TextInput
Error message keys: required, invalid
regex      自定义正则
strip      Defaults to False 去除空格
  • Since version 1.8 has been deprecated and will be removed in Django 2.0 in

    UUIDField(CharField)
    Match type uuid
Default widget: TextInput
Error message keys: required, invalid

ComboField(Field)

Simultaneously using a plurality of authentication verification

Default widget: TextInput
Error message keys: required, invalid
fields=[]
        fields=[CharField(max_length=20), EmailField()] 以邮件的方式匹配,但是长度不超过20
        
MultiValueField(Field)

Abstract class, subclass dictionaries can be implemented to match a plurality of polymerizable value, used to tie MultiWidget

Default widget: TextInput
Error message keys: required, invalid, incomplete
fields=()
require_all_fields    Defaults to True
widget
compress(data_list)
SplitDateTimeField(MultiValueField)

The time string into a valid object type

Default widget: SplitDateTimeWidget
Error message keys: required, invalid, invalid_date, invalid_time
input_date_formats=[]
        ['%Y--%m--%d', '%m%d/%Y', '%m/%d/%y']用于尝试将字符串转换为有效的datetime.date对象的格式列表。
input_time_formats=[]
        ['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']用于尝试将字符串转换为有效的datetime.time对象的格式列表
ModelChoiceField(ChoiceField)
Default widget: Select
Error message keys: required, invalid_choice
queryset
empty_label
to_field_name
Error message keys: required, list, invalid_choice, invalid_pk_value
queryset
to_field_name
ModelMultipleChoiceField(ModelChoiceField)
Default widget: SelectMultiple
Empty value: An empty QuerySet
DurationField(Field)
Default widget: TextInput
Error message keys: required, invalid.
BooleanField(Field)

Boolean

Default widget: CheckboxInput
True or False value.
Error message keys: required
NullBooleanField(BooleanField)
Default widget: NullBooleanSelect
 True, False or None value.
custom

If the built-in can not meet your needs, you can customize custom match type

  • We must inherit django.forms.Field
  • To realize his clean ()
  • Examples of parameters: (required, label, initial, widget, help_text)

Guess you like

Origin www.cnblogs.com/forsaken627/p/12521955.html