Django does form data validation

The code we wrote before did not verify the data entered in the front-end input box. Let's take a look today. If we verify the data of the form form

Verify in the views file

1. First import the forms module

from django import forms

  

2. Create a template class

# 1. Create a template
class loginform(forms.Form):
    # 2. Elements in the template
    name = forms.CharField(min_length=6,error_messages={"required":"User name cannot be empty","min_length":"The minimum length is 6"})
    # require This is the error code

    email = forms.EmailField()

  

Here this error_messages writes the error message, each different error code corresponds to a different error message

3. Use this class in the view function

def login(request):
    if request.method.lower() == "post":
        # 3. Create a template object, and then pass the data to this object
        obj = loginform(request.POST)

        # 4. Start verification

        status= obj.is_valid()
        print(status)

        # 5. Correct information
        success_dict = obj.clean()
        print(success_dict)

        # 6. Wrong information
        failed_dict = obj.errors.as_json()
        print(failed_dict)
        return redirect("/app1/login")
    else:
        return render(request,"login.html")

  

Here, in the data sent by the front desk, the validity of k is the value of name and email.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325206262&siteId=291194637