Django with Select2 remote data example

I have a model (let's call it Animal) that has a ForeignKey to a Genus model. I would like to have a Modelform that allows the user to select an Animal instance. Clearly, there are too many animals for a single select list so I would like the user to be able to filter by genus and then search by animal.

Select2 has an example of using Ajax request to do something oh-so-similar to what I want. Instead of searching for a usr/repo, I would search for a genus/animal. The user might not know the exact genus or the exact animal they want, so both bits need to be searchable. This UI is fine for my needs.

Django-select2 allows me to use Select2 with Django and has a widget that I think I should be able to use. Note that urls.py contains a url(r'^heavy_data/$', heavy_data, name='heavy_data'), so I can access the view method fine.

In my ModelForm's __init__(...), have:

self.fields['animal'] = forms.ModelChoiceField(
    widget=HeavySelect2Widget(data_view='heavy_data'),
    queryset=Animal.objects.all())

And in the views:

def heavy_data(request):
    filtered_animals = {}
    if request.is_ajax():
        import ipdb
        ipdb.set_trace()
        # What next?
    return HttpResponse(json.dumps(filtered_animals))

I am unsure how to pass the whole genus/animal search string form the form to the view. However, I might not even be on the right tracks... Am I? Is there a better way to do what I want?

Upvotes: 2

Views: 3017

Answers (1)

This is actually trivial.

First define a new widget like so:

class MyWidget(ModelSelect2Widget):
    search_fields = ['name__icontains', 'genus__name__icontains']

Then, in your form, use that widget:

class AnimalModelForm(ModelForm):
    class Meta:
        model = Animal
        fields = ['animal', ]
        widgets = {'configurator': MyWidget, }

You can then search either by genus, animal, or both. There is no clever formatting, you just type search terms.

Many thanks to Johannes Hoppe for his help.

Upvotes: 2

Related Questions