Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

django

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.

like image 656
user1993015 Avatar asked Nov 10 '15 22:11

user1993015


2 Answers

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>
like image 161
fedorshishi Avatar answered Sep 28 '22 07:09

fedorshishi


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

like image 26
SuperNova Avatar answered Sep 28 '22 07:09

SuperNova