Django表单:检查唯一名称

时间:2018-05-25 12:59:32

标签: django forms

在我的表单中,我想检查描述符名称是否对于此项目是唯一的。

Models.py

class Descriptor (models.Model):
    project = models.ForeignKey('Project', on_delete=models.CASCADE, default='1')
    name = models.CharField(max_length=1000)

forms.py

class DescriptorForm(forms.ModelForm):
    class Meta:
        model = Descriptor
        fields = ('name','project')
        widgets = {'project': forms.HiddenInput()}

    def clean_name(self):
        name = self.cleaned_data['name']
        project = self.fields['project']
        if Descriptor.objects.filter(project=project, name__iexact=name).exists():
            raise ValidationError("Descriptor with this name already exists")
        return name

我正在

TypeError: int() argument must be a string, a bytes-like object or a number, not
 'ModelChoiceField'

没有project = self.fields['project']project=project thec检查有效,但适用于所有描述符,而不仅仅是连接到此项目的描述符。我需要做些什么来改变它?

2 个答案:

答案 0 :(得分:0)

您应该使用fieldscleaned_data方法中获取project值,而不是clean_name,而是更改字段顺序以在名称验证期间使项目可用:

class DescriptorForm(forms.ModelForm):
    class Meta:
        model = Descriptor
        fields = ('project', 'name')
        widgets = {'project': forms.HiddenInput()}

    def clean_name(self):
        name = self.cleaned_data['name']
        project = self.cleaned_data['project']
        if Descriptor.objects.filter(project=project, name__iexact=name).exists():
            raise ValidationError("Descriptor with this name already exists")
        return name

self.fields['project']返回字段类本身,而不是它的值。

答案 1 :(得分:0)

如果您可以更改模型,则可以使用unique_together lists.stream().mapToInt(x -> x.size()).max().getAsInt() 属性来实现唯一性检查。

Meta

通过此,您的表格将缩减为:

class Descriptor (models.Model):
    project = models.ForeignKey('Project', on_delete=models.CASCADE, default='1')
    name = models.CharField(max_length=1000)

    class Meta:
        unique_together = (
            ('project', 'name'),
        )

在(重要)方面不是:您应该 class DescriptorForm(forms.ModelForm): class Meta: model = Descriptor fields = ('project', 'name') widgets = { 'project': forms.HiddenInput(), } 中使用default='1',因为它需要ForeignKey个实例,而不是字符串。