Reputation: 2580
Hello Im trying to implement chosen.js into my Django project and so far it works great. I only have one issue which I cannot solve. I have a model where "language" is a ChardField
. I wanted to let the User choose more than one language so I tried to use chosen Multiple. Since a Charfield can only hold one Value so I used Django Multiselect. Now the Chosen.js is not working anymore and I have no idea what to do.
Models:
from multiselectfield import MultiSelectField
class UserProfile(models.Model):
language = MultiSelectField(verbose_name=_(u"Content Language"),
max_length=40, choices=settings.LANGUAGES,default='en')`
Forms:
class UserProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields=[
'language',
.....
]
Template:
{% load widget_tweaks %}
{% csrf_token %}
<span>Content language {{ form.language|add_class:"chosen-select" }}</span>
So the question is how do I get the normal chosen.js input field to a multiple chosen field (with Django)? I know there is the possibility to add a multiple field to the forms but this messes up my hole code.
Upvotes: 1
Views: 1283
Reputation: 148
I implemented the chosen multi select by the following:
Forms
class select_language(ModelForm):
#Get data for choice boxes
language_results = language.objects.all()
select_language = forms.ModelMultipleChoiceField(
queryset=language_results,
widget = forms.SelectMultiple(attrs={
'placeholder': "Choose the users(s)",
'class': 'chosen-select',
'multiple tabindex': '4',
}),
)
Template:
....
{% load static %}
<link rel="stylesheet" href="{% static 'chosen.css' %}">
<link rel="stylesheet" href="{% static 'prism.css' %}">
....
{{ select_language.select_language }}
<script type="text/javascript" src="{% static 'chosen.jquery.js' %}"></script>
<script type="text/javascript" src="{% static 'docsupport/prism.js' %}"></script>
<script type="text/javascript" src="{% static 'docsupport/init.js' %}"></script>
Of course you will need to update the locations for the static files. Hopefully this is a good starting direction.
Upvotes: 3