Considering a Django application, I have to apply I18N to the values stored in "Area" table. The values of the field i18n_code points to msgid entries in my locale/en_US/LC_MESSAGES/django.po.
As you can see in my code, Startup model has a ManyToMany field of Area. In my form, area is a CheckboxSelectMultiple widget. How can I, inside my form01.html (template) get the i18n_code, pass to {% trans area.i18n_code %}
so I can get options rendered in proper language?
I checked many questions relative to this subject... but I did not got some clean solution.
Checkout the codes:
models.py:
@python_2_unicode_compatible
class Area (models.Model):
name = models.CharField(max_length = 200)
i18n_code = models.CharField(max_length = 200)
def __str__(self):
return self.name
@python_2_unicode_compatible
class Startup (models.Model):
name = models.CharField(max_length = 200)
# ...
areas = models.ManyToManyField(Area, verbose_name = 'Areas')
def __str__(self):
return self.name
form01.html
<div class="row linhaForm">
<div class="col-lg-4 legenda">
<b>{% trans 'FORM_1_LABEL_AREA' %}</b>
<p>{% trans 'FORM_1_LABEL_AREA_DESCRIPTION' %}</p>
</div>
<div class="col-lg-8">
{% for area in form.areas %}
<div class="checkbox">
{{area}} <-------------------- Here is my problem!
</div>
{% endfor %}
</div>
</div>
forms.py
from django.utils.translation import ugettext_lazy as _
class Step1Form(forms.ModelForm):
class Meta:
model = models.Startup
fields = ['name', 'areas']
widgets = {
'areas': forms.CheckboxSelectMultiple(attrs={'onclick':'onAreaCheckHandler()'}),
'name': forms.TextInput(attrs={'class': 'form-control'}),
}
error_messages = {
'name': {
'required': _("FORM_1_ERROR_NAME_REQUIRED")
},
'areas': {
'required': _("FORM_1_ERROR_AREA_REQUIRED")
}
}
def __init__(self, *args, **kwargs):
super(Step1Form, self).__init__(*args, **kwargs)
if self.instance:
self.fields['areas'].queryset = models.Area.objects.all()
If you help me with this cenario, will help with the other that I have, where I got CharField with choices and ForeignKey fields too, rendered in a Select tag.
I believe this would fix your problem.
{% for area in form.fields.areas.queryset %}
<div class="checkbox">
{% trans area.i18n_code %}
</div>
{% endfor %}