django模型和领域

时间:2014-02-07 11:08:32

标签: django django-forms

我有一个带有一些字段的模型和一个用户作为ForeignKey

class Customer(models.Model):
    #fields
    salesman = models.ForeignKey(User, blank=True, null=True)

和模型表格

class CustomerForm(ModelForm):

    class Meta:
        model = Customer

我希望我的表单验证是否也输入了salesman而不是数据库级别。如果我添加推销员字段

class CustomerForm(ModelForm):
    salesman = forms.ModelChoiceField(required=True, queryset=User.objects.all(), widget=Select(attrs{"class":"form-control"})

    class Meta:
        model = Customer

是否会超越模特推销员领域?我必须覆盖保存方法以将新创建​​的字段值保存到模型默认值吗?或者django表单是否与字段名称相同并正确使用它?

1 个答案:

答案 0 :(得分:0)

您可以重新定义表单的clean方法:

class CustomerForm(ModelForm):
    class Meta:
        model = Customer

    def clean(self, *args, **kwargs):
        cleaned_data = super(CustomerForm, self).clean(*args, **kwargs)
        salesman = cleaned_data.get('salesman')
        if salesman:
            # do something
        else:
            # you can rise form error if need
           msg = u"Salesman is required"
           self._errors["salesman"] = self.error_class([msg])