Tests django_autocomplete_light select2_many_to_many

models.py

 1from django.db import models
 2from six import python_2_unicode_compatible
 3
 4
 5@python_2_unicode_compatible
 6class TModel(models.Model):
 7    name = models.CharField(max_length=200)
 8
 9    test = models.ManyToManyField(
10        "self", blank=True, related_name="related_test_models"
11    )
12
13    for_inline = models.ForeignKey(
14        "self", models.CASCADE, null=True, blank=True, related_name="inline_test_models"
15    )
16
17    def __str__(self):
18        return self.name

forms.py

 1from dal import autocomplete
 2from django import forms
 3
 4from .models import TModel
 5
 6
 7class TForm(forms.ModelForm):
 8    class Meta:
 9        model = TModel
10        fields = ("name", "test")
11        widgets = {
12            "test": autocomplete.ModelSelect2Multiple(
13                "select2_many_to_many_autocomplete"
14            )
15        }

urls.py

 1from dal import autocomplete
 2from django.conf.urls import url
 3from django.views import generic
 4
 5from .forms import TForm
 6from .models import TModel
 7
 8
 9urlpatterns = [
10    url(
11        "test-autocomplete/$",
12        autocomplete.Select2QuerySetView.as_view(
13            model=TModel,
14            create_field="name",
15        ),
16        name="select2_many_to_many_autocomplete",
17    ),
18    url(
19        "test/(?P<pk>\d+)/$",
20        generic.UpdateView.as_view(
21            model=TModel,
22            form_class=TForm,
23        ),
24    ),
25]

test_functional.py

 1from dal.test import case
 2from dal.test import stories
 3from dal_select2.test import Select2Story
 4
 5from .models import TModel
 6
 7
 8class AdminManyToManyTestCase(
 9    Select2Story, case.AdminMixin, case.OptionMixin, case.AutocompleteTestCase
10):
11
12    field_name = "test"
13    inline_related_name = "inline_test_models"
14    model = TModel
15
16    label_selector = ".select2-selection__choice"
17
18    def setUp(self):
19        super(AdminManyToManyTestCase, self).setUp()
20        self.get(url=self.get_modeladmin_url("add"))
21
22    def test_can_create_option_on_the_fly_and_select_existing_option(self):
23        story = stories.CreateOptionMultiple(self)
24
25        option = self.create_option()
26        story.select_option(option.name)
27
28        name = "new option %s" % self.id()
29        story.create_option(name)
30
31        self.enter_text("#id_name", "special %s" % self.id())
32        story.submit()
33
34        story.assert_values(
35            (
36                self.model.objects.get(name=name).pk,
37                option.pk,
38            )
39        )
40        story.assert_labels(
41            (
42                name,
43                option.name,
44            )
45        )

Examples

Example issue 87

../../../../../_images/example_issue_897.png