django validates data with forms

Validate data with
forms Commonly used Field:
Using Field can be the first step in data validation. What type of data do you expect to submit, then what type of Field to use.

CharField:
used to receive text.
parameter:

max_length: The maximum length of this field value.
min_length: The minimum length of this field value.
required: Whether this field is required. Required by default.
error_messages: When a certain condition fails to verify, an error message is given.
EmailField:
Used to receive emails, it will automatically verify whether the emails are legal.
The key of the error message: required, invalid.

FloatField:
used to receive floating-point types, and if the verification is passed, the value of this field will be converted to floating-point types.
parameter:

max_value: the maximum value.
min_value: the minimum value.
The key of the error message: required, invalid, max_value, min_value.

IntegerField:
used to receive integers, and after the verification is passed, the value of this field will be converted to integers.
parameter:

max_value: the maximum value.
min_value: the minimum value.
The key of the error message: required, invalid, max_value, min_value.

URLField:
used to receive a string in url format.
The key of the error message: required, invalid.

Commonly used validators:
When validating a field, you can pass a validators parameter to specify the validator to further filter the data. There are many validators, but we can actually specify many validators through this Field or some parameters. For example, EmailValidator, we can specify it through EmailField, such as MaxValueValidator, we can specify it through the max_value parameter. Here are some commonly used validators:

MaxValueValidator: Validate the maximum value.
MinValueValidator: Validates the minimum value.
MinLengthValidator: Validate the minimum length.
MaxLengthValidator: Validate the maximum length.
EmailValidator: Verify whether it is an email format.
URLValidator: Verify whether it is in URL format.
RegexValidator: If more complex verification is needed, then we can pass the regular expression validator: RegexValidator. For example, if we want to verify whether the mobile phone number is qualified, we can implement it through the following code:
class MyForm(forms.Form):
telephone = forms.CharField(validators=[validators.RegexValidator(“1[345678]\d{9}”, message='Please enter a mobile phone number in the correct format!')])
Custom validation:
Sometimes a field is validated, not a length, a regular expression can be written clearly, and some other complex logic is needed, then we can Perform custom validation on a field. For example, in the registration form verification, we want to verify whether the mobile phone number has been registered, then we need to judge in the database to know. The custom verification method for a field is to define a method, and the name definition rule of this method is: clean_fieldname. If validation fails, a validation error is thrown. For example, to verify whether the mobile phone number in the user table existed in the database before, you can use the following code to achieve:

class MyForm(forms.Form):
telephone = forms.CharField(validators=[validators.RegexValidator(“1[345678]\d{9}”, message='Please enter a mobile phone number in the correct format!')])

def clean_telephone(self):
    telephone = self.cleaned_data.get('telephone')
    exists = User.objects.filter(telephone=telephone).exists()
    if exists:
        raise forms.ValidationError("手机号码已经存在!")
    return telephone

The above is to verify a certain field. If you need to verify multiple fields when verifying data, you can rewrite the clean method. For example, when registering, it is necessary to judge whether the two submitted passwords are equal. Then it can be done with the following code:

class MyForm(forms.Form):
telephone = forms.CharField(validators=[validators.RegexValidator(“1[345678]\d{9}”, message='Please enter a mobile phone number in the correct format!')]) pwd1
= forms.CharField(max_length=12)
pwd2 = forms.CharField(max_length=12)

def clean(self):
    cleaned_data = super().clean()
    pwd1 = cleaned_data.get('pwd1')
    pwd2 = cleaned_data.get('pwd2')
    if pwd1 != pwd2:
        raise forms.ValidationError('两个密码不一致!')

Extract error messages:
If validation fails, there are some error messages that we need to pass to the front end. At this time, we can obtain it through the following attributes:

form.errors: The error message obtained by this attribute is an error message that contains html tags.
form.errors.get_json_data(): This method gets a dictionary-type error message. A dictionary with the name of a field as the key and the error message as the value.
form.as_json(): This method is to dump the dictionary returned by form.get_json_data() into a string in json format for easy transmission.
The error value of the field obtained by the above method is a relatively complex data. For example:
{'username': [{'message': 'Enter a valid URL.', 'code': 'invalid'}, {'message': 'Ensure this value has at most 4 characters (it has 22) .', 'code': 'max_length'}]}
Then if I just want to put the error message in a list instead of a dictionary. At this time, we can define a method to rearrange this data. The example code is as follows:

class MyForm(forms.Form):
username = forms.URLField(max_length=4)

def get_errors(self):
    errors = self.errors.get_json_data()
    new_errors = {}
    for key,message_dicts in errors.items():
        messages = []
        for message in message_dicts:
            messages.append(message['message'])
        new_errors[key] = messages
    return new_errors

In this way, all error messages of a certain field can be directly placed in this list.

Guess you like

Origin blog.csdn.net/qq_17584941/article/details/128801912