【发布时间】:2013-12-04 21:48:08
【问题描述】:
我有一个看起来像这样的表格:
class ContactForm(forms.ModelForm):
error_messages = {
'duplicate_name': 'A backup contact with that name already exists for this location',
'missing_location': 'No location supplied.'
}
class Meta:
fields = ('name', 'notification_preference', 'email', 'phone')
model = Contact
········
def clean_name(self):
# FIXME: Location validation shouldn't be happening here, but it's difficult to get
# form fields for foreign key relationships to play nicely with Tastypie
print dir(self)
if 'location' in self.data:
location = Location.objects.get(pk=self.uri_to_pk(self.data['location']))
else:
raise forms.ValidationError(self.error_messages['missing_location'])
# No duplicate names in a given location
if 'name' in self.cleaned_data and Contact.objects.filter(name=self.cleaned_data['name'], location=location).exists():
raise forms.ValidationError(self.error_messages['duplicate_name'])
return self.cleaned_data
我正在使用它来验证对我的 TastyPie API 的调用。 clean_name 方法旨在防止在将同名联系人发布到同一位置时发生 POST 请求。只要我发出 POST 请求,它就可以完美地工作。
但是,如果我创建一个 PATCH,例如更改已经存在的联系人的电子邮件和电话字段,clean_name 逻辑仍然会被触发。由于给定位置的名称已经存在,因此会引发验证错误。
我应该覆盖clean_name 以外的其他内容吗?我可以更改 PATCH 的工作方式,使其忽略某些验证吗?
【问题讨论】: