Home > database >  Django Inline Tabular admin: delete an object not working
Django Inline Tabular admin: delete an object not working

Time:12-19

I'm using Django admin.TabularInline class inorder to add multiple objects in a Foreinkey relationship as below:

admin.py:

class HeadFlowDatasetInline(admin.TabularInline):
    model = HeadFlowDataset
    extra = 0

class ProductAdmin(admin.ModelAdmin):
    list_display = (
        ...
    )
    search_fields = (
        ...
    )
    fields = (
        ...
    )
    inlines = [HeadFlowDatasetInline]

    def save_model(self, request, obj, form, change):
        obj.created_by = request.user
        obj.last_updated_by = request.user
        obj.save()

    def save_formset(self, request, form, formset, change):
        instances = formset.save(commit=False)
        for instance in instances:
            instance.user = request.user
            instance.save()

Also these are my models for Product and HeadFlowDataset:

class Product(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
    )
    main_model = models.ForeignKey(
        MainModel,
        on_delete=models.SET_NULL,
        null=True,
        verbose_name="نام مدل اصلی پمپ",
    )
    usage = models.ManyToManyField(Usage)
    sub_usage = models.ManyToManyField(SubUsage)
    pump_type = models.ForeignKey(
        PumpType,
        on_delete=models.SET_NULL,
        null=True,
        verbose_name="تیپ پمپ",
    )
    pump_name = models.CharField(
        max_length=255,
        null=False,
        blank=False,
        verbose_name="نام محصول",
        unique=True,
    )
    ... # other fields not related to this question.
    
    def __str__(self):
        return self.pump_name


class HeadFlowDataset(models.Model):
    id = models.UUIDField(
        primary_key=True,
        default=uuid.uuid4,
        editable=False,
    )
    product = models.ForeignKey(
        Product,
        on_delete=models.CASCADE,
    )
    head = models.FloatField()
    flow = models.FloatField()

    def __str__(self):
        return self.product.pump_name

And for this purpose, this approach is working just fine. But the problem occurs when I'm trying to remove a HeadFlowDataset object from the add product object page. As shown in the picture below, there is a checkbox item in front of each HeadFlowDataset object, but checking it and saving does not work. I could not find any other way to make this work neither. Can anyone show me a way to do this? enter image description here

CodePudding user response:

because you set the commit to False then the operations don't run by default like delete and save you can use your formset.deleted_objects to iterate and delete them if have a delete permission

  • Related