Search code examples
djangoinline-formset

Django inline formsets updating a model


I'm pulling my hair out trying to get Django's formsets to work when updating a model.

I've got 2 models, Product and ProductSize. I'm using an inline formset to link my ProductSizes to the Products when adding or edit the Product. Adding the object is fine, but when I trying editing the Product, I can't submit the form. I get [{'id': ['This field is required.']}] output in the print below.

Here are my views:

class ProductAdd(AddModelView):
    model = Product
    form_class = UpdateProductForm
    template_name = 'intake_goods_form.jinja'
    title = 'Add Product Type'
    formset_class = ProductSizesFormSet

    def form_valid(self, form):
        obj = form.save()
        formset = self.formset_class(self.request.POST)
        if formset.is_valid():
            formset.instance = obj
            formset.save()
        else:
            print(formset.errors)
            return self.form_invalid(form)
        return super().form_valid(form)

    def get_context_data(self, **kwargs):
        if self.request.POST:
            formset = self.formset_class(self.request.POST, instance=self.object)
        else:
            formset = self.formset_class(instance=self.object)
        return super().get_context_data(formsets=formset, **kwargs)


product_type_add = ProductAdd.as_view()


class ProductEdit(ProductAdd, UpdateModelView):
    model = Product
    form_class = UpdateProductForm


product_type_edit = ProductEdit.as_view()

And here are my forms:

class UpdateProductForm(SVModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    class Meta:
        model = Product
        exclude = {'material'}


class ProductSizeForm(SVModelForm):
    title = 'Product Type Sizes'

    class Meta:
        model = ProductSize
        fields = ['sku_code', 'bar_code', 'size']


ProductSizesFormSet = forms.inlineformset_factory(Product, ProductSize, ProductSizeForm, extra=1, can_delete=False)

Can anyone help?

Thanks


Solution

  • Okay so I found the solution, and it would have been impossible to figure out from my posted question, sorry.

    In the template, I was only looping through the formset's visible fields. So of course, ID was not included.

    Make sure to include the formset.id field in the template if needed.