How to Select Multiple data from drop down in django form(Field has M2M relation in database)?

Viewed 136

I have one many to many field in my model.py

here in my form the developer field i want to select multiple data and update that in table. some one plese help to achieve that?

1 Answers

You are using the wrong widget for your field. The default form field for a ManyToManyField is a ModelMultipleChoiceField which has SelectMultiple as its default widget, whereas you are using Select as the widget.

The widgets you can use are either SelectMultiple or CheckboxSelectMultiple (You can refer the documentation for all the widgets that are available):

class jiraReg(forms.ModelForm):
    class Meta:
        model = jira
        fields = ['Jira_ID', 'Jira_Story', 'Short_Description', 'Story_Points', 'Sprint','DX4C_Object','Developer','Sandbox']
        widgets = {
            ...
            # Use SelectMultiple below
            'Developer':forms.SelectMultiple(attrs={'class':'form-control', 'id':'Developer'}),
            '...
            }

Also you write fm.save.m2m() in your view which doesn't make much sense. Simply remove that line.


Note: You break various naming conventions in Python in your code. variables / functions are supposed to be named in snake_case, classes in PascalCase. Please have a look at PEP 8 -- Style Guide for Python Code

Related