In django, how do I use a select2 widget for a manytomanyfield?

user1993015 picture user1993015 · Nov 10, 2015 · Viewed 13.1k times · Source

I want to use a select2 widget for a manytomanyfield in django. There are several django/select2 modules, but the documentation is confusing, and I can't find a simple example of what I want. Thanks for any help.

Answer

theodor picture theodor · Dec 30, 2015

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>