我有一个像这样的子类别形式:
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
字段时,如何避免这种情况?
答案 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])