【问题标题】:Form Validation - Clean Method Interfering with PATCH Requests表单验证 - 干扰 PATCH 请求的清理方法
【发布时间】: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 的工作方式,使其忽略某些验证吗?

【问题讨论】:

    标签: python django tastypie


    【解决方案1】:

    是的,如果您要检查字段之间的值,我建议您实现一个通用的def clean(self, data) 来检查值不冲突。

    关于检查重复项,我建议您在 exists() 查询集中使用 .exclude(pk=instance.pk) 以防止错误地将模型更新检测为重复项。查看tastypie validation source,它为正在更新的对象添加了适当的self.instance

    qs = Contact.objects.filter(name=self.cleaned_data.get('name', ''), location=location)
    if self.instance and self.instance.pk:
        qs = qs.exclude(pk=self.instance.pk)
    if qs.exists():
        raise forms.ValidationError(...)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多