Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: combine lazy translation with mark safe in model choices

Yeah, so, I want to store translated choices for my model, but Django disagrees with me on this one. Version of Django is 1.3 and the model and choices look something like this:

from django.db import models
from django.utils.safestring import mark_safe          
from django.utils.translation import ugettext_lazy as _

RATE_CHOICES = (
    ('', _('Choose service rate')),
    ('5cpm_EUR', mark_safe(string_concat('€ 0,05 ', _('per minute')))),
    ('1cpm_EUR', mark_safe(string_concat('€ 0,01 ', _('per minute')))),
)

class Product(models.Model):
    service_rate = models.CharField(_('service rate'), max_length=10, blank=True, choices=RATE_CHOICES)

Also, the choices are used in a modelform (for another model so i had to redeclare the field) like so:

service_rate = forms.ChoiceField(choices=RATE_CHOICES, widget=forms.Select(attrs={'class': 'chzn-select rate-select'}), required=False)

Problem is that no matter what I try; following the stuff on django docs, reversing order of mark_safe and translation, using no lazy translation etc. etc. it always comes down to either the mark_safe working or the translation working. But never both...

How do I combine the two functions properly?

like image 522
Allard Stijnman Avatar asked Feb 22 '13 14:02

Allard Stijnman


1 Answers

Add:

from django.utils import six  # Python 3 compatibility
from django.utils.functional import lazy
from django.utils.safestring import mark_safe
from django.utils.translation import ugettext_lazy as _

mark_safe_lazy = lazy(mark_safe, six.text_type)

And then:

mark_safe_lazy(string_concat('€ 0,05 ', _('per minute')))

This was added to Django 1.4 docs.

like image 107
DhhJmm Avatar answered Sep 21 '22 15:09

DhhJmm