Question

I am developing an multilingual application using Django. One part is to select the type of something using the ContentType API.

As describe in the doc, the ContentType object name is extracted from the verbose_name.

In my case the verbose_name is translated using xgettext_lazy but as it is copyied in the database during the syncdb, there is no translation for ContentType, the verbose_name is not translated.

I would like to be able to change the way the foreign key is displayed in a form.

Do you have any idea of how I can do that ?

Cheers,

Natim

Was it helpful?

Solution 2

Finally here is the solution I found :

def content_type_choices(**kwargs):
    content_types = []
    for content_type in ContentType.objects.filter(**kwargs):
        content_types.append((content_type.pk, content_type.model_class()._meta.verbose_name))

    return content_types

LIMIT_CHOICES_TO = {'model__startswith': 'pageapp_'}

class PageWAForm(forms.ModelForm):
    app_page_type = forms.ModelChoiceField(queryset=ContentType.objects.filter(**LIMIT_CHOICES_TO), 
                                           empty_label=None)

    def __init__(self, *args, **kwargs):
        super(PageWAForm, self).__init__(*args, **kwargs)
        self.fields['app_page_type'].choices = content_type_choices(**LIMIT_CHOICES_TO)

OTHER TIPS

You need to use ugettext_lazy instead of ugettext, and it's not stored in the database, but it's on some .po files. For instance:

from django.utils.translation import ugettext_lazy as _

class Event(models.Model):
    ...

    class Meta:
        verbose_name = _(u'Event')
        verbose_name_plural = _(u'Events')

For code blocks that are loaded on import time, you need to use ugettext_lazy, and for those that are loaded on execution time, you need ugettext. Once you have that, you just need to do a "python manage.py makemessages" and "python manage.py compilemessages"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top