Sud
Sud

Reputation: 135

How to use ModelMultipleChoiceField in django-admin and django-form for SelectMultiple widget

I need to use SelectMultiple widget with ModelMultipleChoiceField in Django-admin.

It's not selecting proper value in django-admin at the time of editing. Please share a working example if possible.

Thanks in advance!!!

In this issue I was not getting desired result and there was no error in my project, so this issue is different.

Upvotes: 2

Views: 5950

Answers (1)

ger.s.brett
ger.s.brett

Reputation: 3308

Here is a simple example. If your model.py looks like:

class YourCategory(models.Model):
    category_name = models.CharField(max_length=100)
    def __unicode__(self):
         return self.category_name

class YourModel(models.Model):
    name = models.CharField(max_length=100)
    included_categories = models.ManyToManyField(Category)
    def __unicode__(self):
         return self.name

You override in the admin.py the field you want as MultipleChoice:

class YourModelForm(forms.ModelForm):
    included_categories = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(),
            queryset = YourCategory.objects.all())#here you can filter for what choices you need

class YourModelAdmin(admin.ModelAdmin):
    form = YourModelForm

Upvotes: 6

Related Questions