Last Updated: February 25, 2016
·
2.015K
· demanuel

Chosen forms in Django

To ensure that all forms of our Django project using the plugin CHOSEN:

Install the plugin django-chosen:

$ pip install -e git+git://github.com/theatlantic/django-chosen.git#egg=django-chosen

Add the app to settings.py:

INSTALLED_APPS = (
    ...
    chosen,
    ....
)

We will build a base form which will inherit the rest of our forms:

from chosen import forms as chosenforms

class ChosenModelForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ChosenModelForm, self).__init__(*args, **kwargs)
        for field in self.fields:
            if self.fields[field].__class__.__name__ in ['ChoiceField', 'TypedChoiceField', 'MultipleChoiceField']:
                choices = self.fields[field].choices
                self.fields[field] = chosenforms.ChosenChoiceField(choices=choices)
            elif self.fields[field].__class__.__name__ in ['ModelChoiceField', 'ModelMultipleChoiceField']:
                queryset = self.fields[field].queryset
                self.fields[field] = chosenforms.ChosenModelChoiceField(queryset=queryset)

class FormA(ChosenModelForm):
    class Meta:
        model = ModelA

class FormB(ChosenModelForm):
    class Meta:
        model = ModelB

Attach css and javascript files needed to the template:

...
{% block extra_js %}
    {{ block.super }}
    {{ form.media }}
    ...
{% endblock %}

et voilà!!

source: http://j.mp/U5eoEw