Search code examples
djangodjango-admindjango-mptt

django admin nested inlines with mptt children


I'm trying to figure out if it's possible to create a ModelAdmin with multiple nested inlines like:

  1. Contract
    • Mainproduct
      • Subproduct1
      • Subproduct2
        • SubSubproduct

And I'm also trying to solve the models with mptt. My models are looking like this:

class Contract(models.Model):    
    contractnumber =  models.CharField(max_length=25)
    field2 =  models.CharField(max_length=25)
    field3 =  models.CharField(max_length=25)
    field4 =  models.CharField(max_length=25)

    def __str__(self):
        return self.field1

    class Meta:
        verbose_name = 'Contract'
        verbose_name_plural = 'Contracts'

class Mainproduct(MPTTModel):
    pr_c_contractnumber = models.ForeignKey(Contract)
    pr_name = models.Charfield(max_length=50)
    productdetails = models.Textfield(max_length=5000)
    pr_sernr = models.CharField(max_length=50)
    parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True,
                            on_delete=models.SET_NULL)

    def __str__(self):
        return self.pr_c_contractnumber, self.pr_name

    class MPTTMeta:
        order_insertation_by = ['pr_sernr']

    class Meta:
        verbose_name = 'Product'
        verbose_name_plural = 'Products'

My admin.py file is looking like this:

class ProductModelInlineForm(forms.ModelForm):
    parent = TreeNodeChoiceField(queryset=Product.objects.all())

class ProductModelInline(admin.TabularInline):
    model = Product
    form = ProductModelInlineForm
    extra = 1

class ProductAdmin(admin.ModelAdmin):
    inlines = [ProductModelInline, ]

class ProductInline(admin.TabularInline):
    model = Product
    extra = 1

class ContractAdmin(admin.ModelAdmin):
    inlines = [ProductInline, ]

Is there a way to create these nested inlines? Am I missing something important?


Solution

  • Just use MPTTModelAdmin and it will do it automatically:

    from mptt.admin import MPTTModelAdmin
    
    admin.site.register(Mainproduct, MPTTModelAdmin)