Felipe Martins
Felipe Martins

Reputation: 21

How to use Many to Many widget presented in Admin page

I want to use the widget presented in Admin page for Group creation in my Modelform (picture below) but I'm failing in do that. group-permission-widget

Does anyone know how can I use a widget like this in my form?

I have two models that have a many-to-many relationship.

I have also created a ModelForm class to get all first_model objects that are related to my second_model.

Upvotes: 0

Views: 144

Answers (1)

Beikeni
Beikeni

Reputation: 900

You can define your field in the ModelForm as a ModelMultipleChoiceField (docs) which will hide most of the implementation details and output the exact same result.

Here is an example of an actual implementation I've made in the past

class InterestForm(forms.ModelForm):
    name = forms.ModelMultipleChoiceField(
        queryset=Interest.objects.all(),
        required=False,
        widget=FilteredSelectMultiple("verbose name", is_stacked=False),
    )
    class Meta:
        model = Interest
        fields = ["name"]

Alternatively, if you want more control over how it's rendered, you can write the html yourself. Make sure to include the multiple property in the select tag:

    <label for="{{ form.my_m2m_field.auto_id }}">{{ form.my_m2m_field.name }}</label>
    <select name="{{ form.my_m2m_field.html_name }}" id="{{ form.my_m2m_field.auto_id }}" multiple>
        {% for item in form.my_m2m_field.field.queryset %}
            <option value="{{ item.pk }}">{{ item.name }}</option>
        {% endfor %}
    </select>

Upvotes: 0

Related Questions