In django, how to use select2 widget for manytomanyfield?

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

+7
django manytomanyfield
source share
2 answers

A good place to start is django-select2 , they have a good example job.

Here I simply define 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 to be displayed in select2 are presented here with the ManyToMany relationship type.

The 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 configure Select2Widget if you need it.

And the final part of html

 {% 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> 
+7
source share

In Django> = 2.0,

The new ModelAdmin.autocomplete_fields attribute and the ModelAdmin.get_autocomplete_fields () method allow you to use the Select2 search widget for ForeignKey and ManyToManyField.

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

+1
source share

All Articles