Using mptt in the admin to assign categories to products in a many to many relationship

72 views
Skip to first unread message

newfoundland

unread,
Aug 5, 2017, 3:51:19 PM8/5/17
to django-mptt-dev
Hi,

I am new to Django (and mptt).

My (truncated) product and category models look like this

class ProductCategory(MPTTModel):
    parent
= TreeForeignKey('self', null=True, blank=True)

class Product(models.Model)
    categories
= TreeManyToManyField(ProductCategory)

In admin.py I want to override the standard SelectMultiple widget with CheckboxSelectMultiple

class ProductAdmin(admin.ModelAdmin):

   formfield_overrides
= {
     
TreeManyToManyField:{'widget':CheckboxSelectMultiple},
   
}
   
....
}

As as aside, can I change the default widget for a particular field, rather than having to override for all (in this example) TreeManyToManyFields? This

The result of this is is that I get a layout as shown in the attached image. What this allows the user to do is add a product to a category, which has children. What I need to show instead in this example is:

Category 1
Category 2 > Category 2 Sub > Category 2 sub sub
Category 3 > Category 3 Sub



With the checkbox id's obviously being the ID of the category (Category 1, Category 2 sub sub, Category 3 sub in this example).

I have tried overriding the CheckboxSelectMultiple class but am having no luck.

Any help much appreciated!
gwnNp.jpg

James Beith

unread,
Aug 6, 2017, 6:33:53 PM8/6/17
to django-mptt-dev
I think what you need to look into is filtering the field's QuerySet to only include leaf nodes (i.e. those who don't have children). You should then get three choices instead of six.
Reply all
Reply to author
Forward
0 new messages