Autocompletion for django-generic-m2m’s RelatedObjectsDescriptor

Model example

Consider such a model, using django-generic-m2m to handle generic many-to-many relations:

from django.db import models

from genericm2m.models import RelatedObjectsDescriptor

class TestModel(models.Model):
    name = models.CharField(max_length=200)

    locations = RelatedObjectsDescriptor()

    def __str__(self):

View example

The View example for QuerySetSequence and Select2 works here too: we’re relying on Select2 and QuerySetSequence again.

Form example

As usual, we need a backend-aware widget that will make only selected choices to render initially, to avoid butchering the database. As we’re using a QuerySetSequence and Select2 for multiple selections, we’ll try QuerySetSequenceSelect2Multiple widget.

Also, we need a field that’s able to use a QuerySetSequence for choices to validate multiple models, and then update the RelatedObjectsDescriptor relations: GenericM2MQuerySetSequenceField.

Finnaly, we can’t use Django’s ModelForm because it doesn’t support non-editable fields, which RelatedObjectsDescriptor is. Instead, we’ll use FutureModelForm.


class TestForm(autocomplete.FutureModelForm):
    locations = autocomplete.GenericM2MQuerySetSequenceField(

    class Meta:
        model = TestModel
        fields = ('name',)