Dmitriy Smirnov
Dmitriy Smirnov

Reputation: 449

Trouble getting django-chosen ChosenSelect widget to work

I'm trying to set up a ModelForm in Django that will use the django-chosen ChosenSelect widget for one of the fields. I have installed django-chosen and this is the code I have:

class TestForm(ModelForm):
    class Meta:
        model = Test
        widgets = {
            'field': chosenwidgets.ChosenSelect(),
        }

However, the specifying the widgets has no effect and the form is outputted the same regardless of whether I define it. Any suggestions?

Upvotes: 2

Views: 1903

Answers (2)

radtek
radtek

Reputation: 36300

Here is my solution with using chosen.js directly. I installed it with bower and then included it in my admin class Media:

class MyModelAdmin(LockableAdmin, admin.ModelAdmin):
    form = MyModelForm # has phase_id field

    class Media:
        js = ('components/chosen_v1.1.0/chosen.jquery.min.js', 'admin_tools/js/chosen_admin.js')
        css = {'all': ('components/chosen_v1.1.0/chosen.min.css', 'admin_tools/css/chosen_admin.css')}

The additional chosen_admin.js and chosen_admin.css files contain my init script and css for making the select look more like django admin. Here are the contents:

chosen_admin.js:

/* Create own jquery namespace */
var django = {
    "jQuery": django.jQuery.noConflict(true)
};
var jQuery = django.jQuery;
var $=jQuery;

$( document ).ready(function() {
    $('#id_phase_id').chosen();
});

chosen_admin.css (optional):

a.chosen-single {
    box-shadow: none;
    border-radius: 0px;
    background: white;
    background-image: none;

}
a.chosen-single span{
    line-height: 18px !important;
}

.vTextField{
    width: 24em;
}

a.chosen-single, .chosen-container.chosen-container-single, .chosen-container-single.chosen-single{
    position: absolute;
    box-shadow: none !important;
    border-radius: 0px !important;
    background: white !important;
    background-image: none !important;
    font-size: 11px !important;
    height: 18px !important;
    padding-left: 2px !important;
}

.chosen-container-single .chosen-single div b {
    background-position: 0px 0px;
}

I got some insights here and made corrections as needed. Also see chosen.js. Hope this helps :)

Upvotes: 3

Alasdair
Alasdair

Reputation: 308949

Are you including the form media in your template?

The example template below assumes that your base template has blocks extrastyle and extrahead where you include CSS and scripts respectively, and that you have included jquery 1.4+ in your base template.

# my_template.html
{% extends "base.html" %}

{% block extrastyle %}
{{ block.super }}
{{ form.media.css }}
{% endblock %}

{% block extrahead %}
{{ block.super }}
{{ form.media.js }}
{% endblock %}

{% block content %}
<form action="." method="post">
    <table>
    {{ form }}
    </table>  
    <p><input type="submit" value="Update" />
</form>  
{% endblock %}

Upvotes: 4

Related Questions