基于类视图的Django表单验证

Ken*_*all 4 forms django validation django-class-based-views

我有一个非常简单的基于类的视图:

在views.py中:

class IncidentEdit(UpdateView):
    model=Incident
    fields = visible_field_list
    sucess_url = '/status'
Run Code Online (Sandbox Code Playgroud)

工作得很好.我有关联CreateView,DeleteView等等我可以创建编辑和删除记录.现在要微调项目,我需要添加字段验证.

我的问题:当我将视图基于'model='而不是'form='?时,我在哪里放置基本验证代码?

我可以改变所有内容以使用基于表单的视图,但整个想法是保持简单并且它有效,我只是没有表单验证,除了在模型声明中定义的基本"字段必需"类型验证.

例如,我需要确保一个字段等于另外两个字段的总和.喜欢,

ClassRoomTotal = NumBoys + NumGirls

如果总和与总数不匹配,validation error则为该ClassRoomTotal字段筹集.

提前致谢.
我知道这是一个简单的答案.

建议如"你不能这样做,你必须使用form=IncidentForm和定义一个表单类." 有助于.

Vin*_*kal 12

class IncidentEdit(UpdateView):

    ...

    def form_valid(self, form):
        if form.cleaned_data['email'] in \
        [i.email for i in Incident.objects.exclude(id=get_object().id)]:
            # Assume incident have email and it should be unique !!
            form.add_error('email', 'Incident with this email already exist')
            return self.form_invalid(form)
        return super(IncidentEdit, self).form_valid(form)
Run Code Online (Sandbox Code Playgroud)

此外,希望这个链接有用. http://ccbv.co.uk/projects/Django/1.7/django.views.generic.edit/UpdateView/

  • 这真的很有帮助。只是想问一下,与声明自己的表单相比,这种方法在任何方面都不太有效吗?给一个form_class? (2认同)

aum*_*umo 5

好,

你做不到,你必须使用 form = IncidentForm

或至少它是最简单的解决方案。

请注意,您必须使用form_class = IncidentForm,而不是form = IncidentForm保持model = Incident

我认为使用ModelForm不会增加项目的复杂性,这正是他们的用例。用另一种方式做会使事情变得复杂。

它可以很简单:

class IncidentForm(ModelForm):
    class Meta:
        model = Incident
        # Define fields you want here, it is best practice not to use '__all__'
        fields = [...]

    def clean(self):
        cleaned_data = super(IncidentForm, self).clean()

        field_1 = cleaned_data.get('field_1')
        field_2 = cleaned_data.get('field_2')
        field_3 = cleaned_data.get('field_3')

        # Values may be None if the fields did not pass previous validations.
        if field_1 is not None and field_2 is not None and field_3 is not None:
            # If fields have values, perform validation:
            if not field_3 == field_1 + field_2:
                # Use None as the first parameter to make it a non-field error.
                # If you feel is related to a field, use this field's name.
                self.add_error(None, ValidationError('field_3 must be equal to the sum of field_1 and filed_2'))

        # Required only if Django version < 1.7 :
        return cleaned_data


class IncidentEdit(UpdateView):
    model = Incident
    form_class = IncidentForm
    fields = visible_field_list
    success_url = '/status'
Run Code Online (Sandbox Code Playgroud)