类似对象的表单确认ValidationError

时间:2015-02-22 11:49:19

标签: django django-forms

在保存对象之前,我想添加一条验证警告消息,询问最终用户是否确实要继续,并给出从数据库返回的类似数据。

例如,当最终用户添加Hospital时,Hospital中已存在一个或多个zipcode个对象,则应提供ValidationError说明像Following hospitals in zipcode XX were already found: YYY, ZZZZ. Hit submit again to save if you're sure you want to add another one.

这样的东西

我尝试使用下面的表单,通过添加字段Verified(设置为HiddenInput)来实现此目的。虽然我似乎无法修改该字段。

class CreateHospitalForm(forms.ModelForm):

    verified = forms.BooleanField(widget=forms.HiddenInput, required=False)

    def clean(self):
        cleaned_data = self.cleaned_data

        zipcode = cleaned_data.get('zipcode')
        verified = cleaned_data.get('verified')

        existing_hospitals = Hospital.objects.filter(zipcode=zipcode)

        if existing_hospitals and not verified:
            cleaned_data['verified'] = True  # <<< here I'd like to set verified to True so I don't get the below warning a 2nd time when saving the form
            raise ValidationError(u"Following hospitals already exist in this zipcode: " + ', '.join([str(x) for x in existing_hospitals] + ". Are you sure you want to add another one? Then hit submit again.")

        return cleaned_data

    class Meta:
        model = Hospital
        fields = ('name', 'street_and_number', 'zipcode', 'town', 'country', 'email', 'web', 'comments', 'verified')

知道如何解决这个问题吗? 使用Django 1.7。

编辑:我的观点非常标准,并按要求进入下方:

class CreateHospitalView(generic.CreateView):

    model = Hospital
    template_name = 'hosp_add.html'
    form_class = CreateHospitalForm

    def get_success_url(self):
        return reverse('hosp_detail', args=(self.object.id,))

1 个答案:

答案 0 :(得分:0)

这是你的答案。将干净方法更新为此(请参阅代码中的注释)。

def clean(self):
    cleaned_data = self.cleaned_data

    zipcode = cleaned_data.get('zipcode')
    verified = cleaned_data.get('verified')

    existing_hospitals = Hospital.objects.filter(zipcode=zipcode)

    if existing_hospitals and not verified:
        self.data = self.data.copy()  # self.data is immutable, so we make a copy to get around this
        self.data['verified'] = True  # instead of self.cleaned_data['verified'] = True
        raise ValidationError(u"Following hospitals already exist in this zipcode: " + ', '.join([str(x) for x in existing_hospitals] + ". Are you sure you want to add another one? Then hit submit again.")

    return cleaned_data