忽略编辑视图上的验证器

时间:2016-05-06 18:45:39

标签: python django django-forms

我有一个像这样的子类别形式:

class SubcategoryForm(forms.Form):
    name = forms.CharField(
        widget=forms.TextInput(attrs={'class' : 'form-control'}), 
        max_length=100,
        label='Subcategory',
        validators=[unic_subcategory]
    )
    category = forms.ModelChoiceField(
        widget=forms.Select(attrs={'class' : 'form-control'}),
        queryset = Category.objects.filter(delete=False),
        label='Category'
    )

验证器功能如下所示:

def unic_subcategory(value):
    exist = Subcategory.objects.filter(nome=value)
    if exist:
        raise ValidationError(u"Duplicated subcategory '%s' are not allowed" % value)

当用户创建新的子类别并且已存在具有相同名称的子类别时,此方法有效。当用户尝试编辑category字段而不是name字段时出现问题。表单会引发错误,因为name字段已存在。

当用户编辑category字段时,如何避免这种情况?

2 个答案:

答案 0 :(得分:1)

验证工具不适合此工作。验证器旨在消除普遍不适合给定字段的内容。如果您需要检查更复杂的条件,请添加一个干净的方法:

def clean_name(self):
    value = self.cleaned_data.get('name')
    if self.instance and self.instance.name == value:
        return  # name didn't change, skip the check
    if Subcategory.objects.filter(name=value).exists():
        raise ValidationError(u"Duplicated subcategory '%s' is not allowed" % value)

答案 1 :(得分:-2)

您只需为category添加验证。

def unic_subcategory(name, categ):
    subc_name = Subcategory.objects.filter(name=name)
    subc_categ = Subcategory.objects.filter(categ=categ)
    if all([exist, categ]):
        raise ValidationError(u"Duplicated subcategory '%s' and category %s are not allowed" % [name, categ])