I'm working on a Django app that includes some mptt
based tree models.
I have these models (simplified):
class Asset_Type(MPTTModel):
parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children', verbose_name='Parent')
name = models.CharField(max_length=64, unique=True, verbose_name='Asset Type Name')
class Asset(models.Model):
name = models.CharField(max_length=64, unique=True, verbose_name='Asset Name')
type = models.ForeignKey(Asset_Type, on_delete=models.CASCADE, blank=False, null=False)
I have these admin classes declared (simplified):
class Asset_TypeAdmin(DraggableMPTTAdmin):
mptt_level_indent = 20
admin.site.register(models.Asset_Type, Asset_TypeAdmin)
class AssetAdmin(admin.ModelAdmin):
list_display = ['name','type']
list_display_links = ['name']
admin.site.register(models.Asset, AssetAdmin)
Everything works almost perfect, except this:
When I add a new asset I get a template/form with a drop-down list where I can select the Asset_Type. The issue is that the drop-down list is of the class ModelChoiceField
so it does not show the tree hierarchy. It shows this in the drop-down list:
---------
Root 1
Child 1.1
Child 1.1.1
Root 2
Child 2.1
Child 2.1.1
I would like it to be class TreeNodeChoiceField
so it shows this:
Root 1
--- Child 1.1
------ Child 1.1.1
Root 2
--- Child 2.1
------ Child 2.1.1
I've found information related to this here: Django docs, but honestly I have no clue on how/where should I tell Django that the field to use in the add/change form should be TreeNodeChoiceField
. I've successfully overridden the change_form.html template for the admin for the assets class of my app (creating ./project/app/templates/admin/app/asset/change_form.html
) but I cannot find where to specify in that file (or anywhere else) what's the field to use.