【发布时间】:2019-11-11 07:42:53
【问题描述】:
我正在尝试使用电子邮件作为字段来更新 django ModelForm。在创建表单中,我正在检查该字段是否已存在于数据库中,如果存在则引发验证错误。该部分按预期工作。
但是,如果我在更新表单中使用相同的检查,则会引发验证错误,因为现有记录具有给定的电子邮件。是否有直接的方法来确保此验证?
forms.py
class MyObjCreateForm(forms.ModelForm):
first_name = forms.CharField(max_length=50, label='First name')
last_name = forms.CharField(max_length=50, label='Last name')
email = forms.EmailField(label='Email')
location = forms.ChoiceField(choices=TP_TM_Location, label='Location')
designation = forms.ChoiceField(choices=TP_TM_Designation, label='Designation')
date_of_joining = forms.DateField(label='Date of joining',
widget=forms.TextInput(attrs={'type': 'date'}),
initial=date.today())
username = forms.CharField(label='Login username')
password = forms.CharField(widget=forms.PasswordInput(), label='Login password')
current_status = forms.ChoiceField(choices=TP_Status, label='Current status')
def clean_email(self):
email = self.cleaned_data.get('email')
try:
match = MyObj.objects.get(email=email)
raise forms.ValidationError("email already exists in system. Please check the existing list.")
except MyObj.DoesNotExist:
return email
class MyObjUpdateForm(forms.ModelForm):
first_name = forms.CharField(max_length=50, label='First name')
last_name = forms.CharField(max_length=50, label='Last name')
email = forms.EmailField(label='Email')
location = forms.ChoiceField(choices=TP_TM_Location, label='Location')
designation = forms.ChoiceField(choices=TP_TM_Designation, label='Designation')
date_of_joining = forms.DateField(label='Date of joining',
widget=forms.TextInput(attrs={'type': 'date'}),
initial=date.today())
current_status = forms.ChoiceField(choices=TP_Status, label='Current status')
username = forms.CharField(label='Login username')
def clean_email(self):
email = self.cleaned_data.get('email')
try:
match = MyObj.objects.get(email=email)
raise forms.ValidationError("email already exists in system. Please check the existing list.")
except MyObj.DoesNotExist:
return email
谢谢,
【问题讨论】:
标签: django validation django-forms