Search code examples
djangodjango-admin

how to add functionality of choose_all and remove_all functionality for a model in django-admin


enter image description here I need to add the Choose all and Remove all functionality to one of the django model in the admin view. but not finding any documentation.

I am creating Food table:

<group1->
name:vegetarian

food 
----
vegetables
nuts
greens
chicken
egg


<group2->
name: non-veg

food 
----
vegetables
nuts
greens
chicken
egg

like above i need to choose the food-items and create a group. i want to display like groups option with choose_all/remove_all options.


Solution

  • I referred the official django code for Groups. followed the same, and it just worked great. Here is how i did.

    class FoodPermission(models.Model):
        name = models.CharField(max_length=150)
    
        def __str__(self):
            return str(self.url_name)
    
    
    class FoodGroup(models.Model):
        name = models.CharField(max_length=150)
        permissions = models.ManyToManyField(FoodPermission, blank=True)
    
        def __str__(self):
            return str(self.name)
       
    

    In the admin.py.

    The following code is copied from official django source and just changed class name and commented one line.

    class FoodGroupAdmin(admin.ModelAdmin):
        search_fields = ("name",)
        ordering = ("name",)
        filter_horizontal = ("permissions",)
    
    
    admin.site.register(FoodGroup, FoodGroupAdmin)
    

    with those changed everything worked like charm.