FormView Django中的ValidationError

时间:2015-11-08 11:31:14

标签: python django django-forms

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

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)

它可以工作,我得到错误页面,但我更喜欢用重新加载的表单在模板中显示错误。 此外,还有一种内置方法可以ValidationError获取FormView吗?我的意思是,不从forms导入django

感谢名单。

修改

好吧,我已经决定以其他方式完成所有操作 - 使用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,一切似乎都没问题,但这次表格只是保存而没有任何错误。

1 个答案:

答案 0 :(得分:1)

在表单的$(document).ready(function() { var date = new Date(); // today using client's timezone date.setDate(date.getDate() + 1); // move to tomorrow date.setUTCHours(11,0,0,0); // set time using UTC(GMT) timezone $('#next-shipment').html(date.toLocaleString()); });方法中提升ValidationError是正确的方法。

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

ValidationError