管理员错误触发器中的 BaseInlineFormSet clean 方法?

BaseInlineFormSet clean method in admin false trigger?

我正在尝试更新 Admin 中的一个字段,但它从我在 forms.py 中定义如下的 clean 方法引发验证错误:

class BasePhoneFormSet(BaseInlineFormSet):

    def clean(self):
        super(BasePhoneFormSet, self).clean()
        if any(self.errors):
            return

        phone_numbers = []
        for form in self.forms:
            if form.cleaned_data.get('number') in phone_numbers:
                raise forms.ValidationError(
                    'Duplicate Entry')
            phone_numbers.append(form.cleaned_data.get('number'))



PhoneFormSet = inlineformset_factory(
    Post, 
    Phone,
    formset=BasePhoneFormSet,
    form=PostForm, 
    fields = ('number',), 
    can_delete=False, # admin still shows delete next to the phone number
    extra=0,
    validate_min=True,
    min_num=1,

)

此代码在视图中有效,但在管理员中,我无法更新或添加任何 phone 数字,因为它会为重复条目引发相同的 ValidationError。

这是我的 models.py

class Post(TimeStampedModel, models.Model):
    unique_id = models.CharField(max_length=6, unique=True)
    user = models.ForeignKey(User, related_name='posts')
    city = models.ForeignKey(City, related_name='posts')

class Phone(TimeStampedModel, models.Model):
    number = models.CharField(
        validators=[phone_regex],  max_length=15)
    post = models.ForeignKey(Post)

这是admin.py

class PhoneInline(admin.StackedInline):
    model = Phone
    formset = PhoneFormSet

class PostAdmin(admin.ModelAdmin):
    inlines = [
        PhoneInline,
    ]

我在 models.forms 中查看了 BaseInlineFormSet,但我更困惑了。

class PhoneInline(admin.StackedInline):
    model = Phone
    formset = BasePhoneFormSet
    fields = ('number',)
    can_delete = False
    extra = 0
    min_num = 1