Django - Form 구성 요소 검증

2896 단어
예:
from django import forms

class FM(forms.Form):

    #  form  name 
    username = forms.CharField()
    pwd = forms.CharField()
    email = forms.EmailField() #  


    pass

def fm(request):

    if request.method == 'GET':

        return render(request, 'cookie/fm.html')
    elif request.method == 'POST':

        #  
        #  
        #  : 
        #  : 
        obj = FM(request.POST)
        r1 = obj.is_valid() #  

        if r1:
            print (obj.cleaned_data)
        else:
            print (obj.errors)

        return redirect('/cookie/fm/')

오류가 있으면 다음과 같이 인쇄합니다.
  • email
    • Enter a valid email address.

인쇄: print (obj.errors) 결과:
{"username": [{"message": "This field is required.", "code": "required"}], "pwd": [{"message": "This field is required.", "code": "required"}], "email": [{"message": "This field is required.", "code": "required"}]}


사용자 정의 오류 정보
from django import forms

class FM(forms.Form):

    #  form  name 
    username = forms.CharField(error_messages={'required':' '})
    pwd = forms.CharField(error_messages={'required':' '})
    email = forms.EmailField(error_messages={'required':' '}) #  


예: 잘못된 정보를 전달합니다:views.py
class FM(forms.Form):

    #  form  name 
    username = forms.CharField(error_messages={'required':' '})
    pwd = forms.CharField(
        error_messages={'required':' ', 'min_length':' 6 ', 'max_length':' 12 '},
        min_length=6,
        max_length=12,
    )
    email = forms.EmailField(error_messages={'required':' '}) #  


def fm(request):

    if request.method == 'GET':

        return render(request, 'cookie/fm.html')
    elif request.method == 'POST':

        #  
        #  
        #  : 
        #  : 
        obj = FM(request.POST)
        r1 = obj.is_valid() #  

        if r1:
            print (obj.cleaned_data)
        else:
            return render(request, 'cookie/fm.html', {'obj':obj})

        return redirect('/cookie/fm/')

템플릿:

    
{% csrf_token %}

{{ obj.errors.username.0 | add:' -- error --' }}

{{ obj.errors.pwd.0 }}

{{ obj.errors.email.0 }}

좋은 웹페이지 즐겨찾기