'django admin Inline model is not storing id for related table

I've combine two models into one in admin panel using admin.TabularInline and following is my code that i've tried as far my knowledge.

class ProdutImageTabulurInline(admin.TabularInline):
    model = ProductImage
    exclude = ['user', 'name', 'status']

@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
    inlines = [
        ProdutImageTabulurInline
    ]

    # For Do operation before save operation
    def save_model(self, request, obj, form, change):
        obj.user = request.user
        return super().save_model(request, obj, form, change)

    # https://stackoverflow.com/questions/59580458/how-can-i-access-model-instance-in-save-related-method-of-modeladmin-class
    def save_related(self, request, form, formsets, change):
        obj = form.instance
        obj.user = request.user
        super(ProductAdmin, self).save_related(request, form, formsets, change)

I've hidden the User field from ProductImages since i want that it should store default user id as logged in user id.

So i used save_model for product table and it store user_id as expected but i want that in products image table too, and which is not working



Solution 1:[1]

I've used the save_formset method instead save_related My code looks something like this and it works

def save_formset(self, request, form, formset, change):
    for inline_form in formset.forms:
        inline_form.instance.user = request.user
        inline_form.instance.name = "sample name"
    super().save_formset(request, form, formset, change)
  • save_related : this is called once after model save with save_model
  • save_formset : this will be called many times during each update, once for every inline defined on your ModelAdmin.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TarangP