我有一个带有一些字段的模型和一个用户作为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表单是否与字段名称相同并正确使用它?
答案 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])