所以我有以下表格
class SignUpForm(UserCreationForm):
email = forms.EmailField(required=True, widget=forms.EmailInput(attrs={
'class': tailwind_class
}))
password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': tailwind_class}))
password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class': tailwind_class}))
company_id = forms.CharField(label='Company Identifier',
widget=forms.PasswordInput(attrs={'class': tailwind_class}))
class Meta:
model = get_user_model()
fields = ('email', 'password1', 'password2', 'company_id')
# Custom validator for the company id
def clean_company_id(self):
company_id = self.cleaned_data['company_id']
if not Company.objects.get(id=company_id):
raise ValidationError("This Company ID doesn't exist")
# Return value to use as cleaned data
return company_id
其驗證器除了顯示錯誤訊息以防它不驗證之外起作用。
這是我的模板:
<form class="form shadow-2xl min-w-[360px] max-w-[360px] p-4 bg-woys-purple rounded-lg text-white" method="post" action=".">
{% csrf_token %}
<div class="error-wrapper mb-2">
<div class="errors text-woys-error-light text-center">{{ form.errors.email }}</div>
<div class="errors text-woys-error-light text-center">{{ form.errors.password2 }}</div>
<div class="errors text-woys-error-light text-center">{{ form.non_field_errors }}</div>
</div>
...
uj5u.com熱心網友回復:
這行不通。
當你這樣做時:
SomeModel.objects.get(...)
并且該物件在 get() filtet 引數中不存在,它會引發SomeModel.DoesNotExist因此嘗試將其更改.get()為 a filter(...).exists(),這樣您將獲得自定義錯誤。
我指的是更改這行代碼:
if not Company.objects.get(id=company_id):
此外,如果您只想更新錯誤訊息,您可以指定和覆寫每個欄位的訊息以及該欄位型別可能發生的每種型別或錯誤。
請參閱之前回答的這篇文章,其中描述了如何做到這一點:
使用模型表單創建自定義錯誤訊息
另外我剛剛注意到,在您的模板中,您實際上并未顯示該欄位的錯誤,因此請添加該行以顯示公司 ID 的欄位錯誤
<div class="errors text-woys-error-light text-center">{{ form.errors.company_id }}</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/518170.html
