Django: Custom BaseInlineFormSet. Extra forms

I'm trying to implement an inline for the Product model admin, so that in addition to the forms for existing ProductAttribute relationships, forms for all attributes of the category of the product currently being edited are also added by default. The problem is that while the forms are there, saving doesn't result in creating the ProductAttribute relationship in the database, and the cleaned_data of these forms is empty.

My code: admin.py

...
class ProductAttributeInline(admin.TabularInline):
    model = ProductAttribute
    formset = ProductAttributeInlineFormset
    extra = 0
    fields = ('attribute', 'value')
    readonly_fields = ('attribute',)
    can_delete = False

    def has_add_permission(self, request, obj=None):
        return False


@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    list_display = (
        'name',
        'category',
        'price',
        'sku',
        'created_at',
        'updated_at'
    )
    search_fields = ('name', 'sku')
    list_filter = ('category',)
    inlines = (ProductAttributeInline,)
...

forms.py

from django import forms

from .models import ProductAttribute


class ProductAttributeInlineFormset(forms.models.BaseInlineFormSet):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self.instance and self.instance.pk:
            category = self.instance.category
            if category:
                attributes = category.attributes.all()
                existing_attributes = set(
                    self.queryset.values_list('attribute', flat=True)
                )
                for attribute in attributes:
                    if attribute.id not in existing_attributes:
                        form_index = (
                            len(self.forms) + len(existing_attributes) - 1
                        )
                        form = self._construct_form(
                            instance=ProductAttribute(
                                product=self.instance,
                                attribute=attribute,
                            ),
                            i=form_index
                        )
                        self.forms.append(form)
            self.total_forms = len(self.forms)

I noticed that 'attributes-TOTAL_FORMS' in form.data is equal to 1, but I couldn't find a way to increase this value.

Вернуться на верх