[英]Client-Side Verification Django
我是 Django 的新手,我制作了一個擴展 UserCreationForm 的表單,我想驗證客戶端的輸入。 我怎樣才能做到這一點? 當我驗證 password1 時,它工作得很好,但由於某種原因,我無法檢查字段是否丟失。 提前致謝。
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
def validate(self,password):
return self.short_enough(password) and self.has_lowercase(password) and self.has_uppercase(password) and self.has_numeric(password) and self.has_special(password)
def short_enough(self,pw):
return len(pw) == 8
def has_lowercase(self,pw):
'Password must contain a lowercase letter'
return len(set(string.ascii_lowercase).intersection(pw)) > 0
def has_uppercase(self,pw):
'Password must contain an uppercase letter'
return len(set(string.ascii_uppercase).intersection(pw)) > 0
def has_numeric(self,pw):
'Password must contain a digit'
return len(set(string.digits).intersection(pw)) > 0
def has_special(self,pw):
'Password must contain a special character'
return len(set(string.punctuation).intersection(pw)) > 0
def clean(self):
cleaned_data = super(UserRegisterForm, self).clean()
username = cleaned_data.get('username')
email = cleaned_data.get('email')
password1 = cleaned_data.get('password1')
password2 = cleaned_data.get("password2")
if username == None or email == None or password1 == None or password2 == None:
raise forms.ValidationError("Some fields are missing" )
if not self.validate(password1):
raise forms.ValidationError("Password must be 8 characters(1 upper, 1 lower, 1 number, 1 special character)" )
else:
return cleaned_data
這是我的 HTML 文件,問題是我使用的是 {{ form }} 而不是 HTML 輸入:
{% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST" > {% csrf_token %} <fieldset class="form-group" aria-required="true"> <legend class="border-bottom mb-4"> Join Today </legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit" > Sign Up </button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> Already have an account? <a class="ml-2" href="{% url 'login' %}" >Sign In</a> </small> </div> </div> {% endblock content %}
好的,您的模板看起來不錯,只是在您的表單中添加了一些內容。
為了簡化代碼,我將required=True
添加到您定義的 email 字段並將相同的參數設置到__init__
字段的 rest 方法中,這將根據需要執行所有字段,您可以擺脫自定義“空值”驗證在clean
的
class UserRegisterForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['username'].required = True
self.fields['password1'].required = True
self.fields['password2'].required = True
def validate(self,password):
return self.short_enough(password) and self.has_lowercase(password) and self.has_uppercase(password) and self.has_numeric(password) and self.has_special(password)
def short_enough(self,pw):
return len(pw) == 8
def has_lowercase(self,pw):
'Password must contain a lowercase letter'
return len(set(string.ascii_lowercase).intersection(pw)) > 0
def has_uppercase(self,pw):
'Password must contain an uppercase letter'
return len(set(string.ascii_uppercase).intersection(pw)) > 0
def has_numeric(self,pw):
'Password must contain a digit'
return len(set(string.digits).intersection(pw)) > 0
def has_special(self,pw):
'Password must contain a special character'
return len(set(string.punctuation).intersection(pw)) > 0
def clean(self):
cleaned_data = super(UserRegisterForm, self).clean()
password1 = cleaned_data.get('password1')
password2 = cleaned_data.get("password2")
if not self.validate(password1):
raise forms.ValidationError("Password must be 8 characters(1 upper, 1 lower, 1 number, 1 special character)" )
else:
return cleaned_data
另一方面,要進行單字段驗證,我建議您向用戶 django 提供方法clean_<fieldname>
,在此處查看文檔 --> https://docs.djangoproject.com/en/3.1/ref/forms/validation /#cleaning-a-specific-field-attribute
當您使用 django crispy forms 時,您可以在表單定義中包含提交按鈕以及表單標簽,它會將所有表單 DOM 封裝在您的 python 代碼中,我認為這很棒,請查看文檔 --> https: //django-crispy-forms.readthedocs.io/en/latest/layouts.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.