django form.is_valid 判断多个字段不能同时相同

models 中 设置 Meta unique_together(models.py):

class Item(models.Model):
    text = models.TextField(default='')
    list = models.ForeignKey(List, default=None)
    class Meta:
        ordering = ('id',)
        unique_together = ('list', 'text')
    def __str__(self):
        return self.text

django.db.utils.IntegrityError: UNIQUE constraint failed: lists_item.list_id,
lists_item.text

ModelForm 中设置 instance(forms.py)

class ItemForm(forms.models.ModelForm):
    class Meta:
        model = Item
        fields = ('text',)
        widgets = {
            'text': forms.fields.TextInput(attrs={
                'placeholder': 'Enter a to-do item',
                'class': 'form-control input-lg',
            }),
        }
        error_messages = {
            'text': {'required': EMPTY_ITEM_ERROR}
        }
    def save(self, for_list):
        self.instance.list = for_list
        return super().save()

class ExistingListItemForm(ItemForm):
    def __init__(self, for_list, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.instance.list = for_list
    def validate_unique(self):
        try:
            self.instance.validate_unique()
        except ValidationError as e:
            e.error_dict = {'text': [DUPLICATE_ITEM_ERROR]}
            self._update_errors(e)
    def save(self):
        return forms.models.ModelForm.save(self)

这样就可以在表单提交后检查是否有不唯一的字段了。

你可能感兴趣的:(django form.is_valid 判断多个字段不能同时相同)