FormView Django 中的验证错误

ValidationError in FormView Django

FormView 中引发 ValidationError 并将其传递给具有重新加载表单的模板的正确方法是什么? 目前我有这个:

class ProfileUpdateView(FormView):
    template_name = 'profile_update.html'
    form_class = UserDetailForm
    success_url = '/profile/'

    def form_valid(self, form):
        userdetail = form.save(commit = False)
        try:
            already_exist_info = UserDetail.objects.get(document_type=userdetail.document_type,
                series=userdetail.series, number=userdetail.number)
            raise forms.ValidationError("Document already exists in DB")
        except UserDetail.DoesNotExist:
            [... some stuff here ...]
            userdetail.save()
        return super(ProfileUpdateView, self).form_valid(form)

它工作正常,我收到了错误页面,但我更愿意在模板中以重新加载的形式显示错误。 此外,是否有内置方法可以在 FormView 中获取 ValidationError?我的意思是,不从 django.

导入 forms

谢谢。

编辑

好吧,我决定用其他方式解决所有问题 - 使用 clear() 方法。所以现在我有了这个:

views.py

class ProfileUpdateView(FormView):
    template_name = 'profile_update.html'
    form_class = UserDetailForm
    success_url = '/profile/'

    def form_valid(self, form):
        userdetail = form.save(commit = False)
        #[... some stuff ...]
        userdetail.save()
        return super(ProfileUpdateView, self).form_valid(form)

forms.py

class UserDetailForm(forms.ModelForm):
    class Meta:
        model = UserDetail
        exclude = ('user', )

    def clean(self):
            cleaned_data = super(UserDetailForm, self).clean()
            document_type = cleaned_data.get("document_type")
            series = cleaned_data.get("series")
            number = cleaned_data.get("number")
            try:
                already_exist_info = UserDetail.objects.get(document_type=document_type,
                    series=int(series), number=number)
                raise forms.ValidationError("Document already exists in DB")
            except:
                pass
            return cleaned_data

根据 docs,一切似乎都很好,但是这次表格保存没有任何错误。

在表单的 clean 方法中提高 ValidationError 是正确的做法。

你的问题是你正在捕获 所有 异常,包括 ValidationError。如果您更改代码以捕获更具体的异常,那么它应该可以工作。

try:
    already_exist_info = UserDetail.objects.get(
        document_type=document_type,
        series=int(series), 
        number=number,
    )
    raise forms.ValidationError("Document already exists in DB")
except UserDetail.DoesNotExist:
    pass
return cleaned_data