[Fixed]-In django, how do I use a select2 widget for a manytomanyfield?

12👍

Good place to start is django-select2, they have a good work example also.

Here I just figure out the main idea in the context of their example

model

@python_2_unicode_compatible
class Album(models.Model):
    title = models.CharField(max_length=255)
    artist = models.ForeignKey(Artist)
    featured_artists = models.ManyToManyField(Artist, blank=True, related_name='featured_album_set')
    primary_genre = models.ForeignKey(Genre, blank=True, null=True, related_name='primary_album_set')
    genres = models.ManyToManyField(Genre)

    def __str__(self):
        return self.title

The fields what are will be mapped to the select2 presented here with ManyToMany relationship type.

form

class AlbumSelect2WidgetForm(forms.ModelForm):
    class Meta:
        model = models.Album
        fields = (
            'artist',
            'primary_genre',
        )
        widgets = {
            'artist': Select2Widget,
            'primary_genre': Select2Widget,

        }

It is very easy to customize Select2Widget, if it will be need.

And the final – html part

{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
  {{ form.media.css }}
  <style type="text/css">
    select {
      width: 200px;
    }
  </style>
</head>
<body>
<form method="post" action="">
  {% csrf_token %}
  {{ form }}
  <input type="submit" value="Submit Form"/>
</form>
<script src="{% static '//code.jquery.com/jquery-2.1.4.min.js' %}"></script>
<script type="text/javascript">
  window.onerror = function (msg) {
    $("body").attr("JSError", msg);
  }
</script>
{{ form.media.js }}
</body>

9👍

In Django >= 2.0,

The new ModelAdmin.autocomplete_fields attribute and
ModelAdmin.get_autocomplete_fields() method allow using an Select2
search widget for ForeignKey and ManyToManyField.

Source : https://docs.djangoproject.com/en/2.0/releases/2.0/#minor-features

Leave a comment