Django: combine lazy translation with mark safe in model choices
Asked Answered
P

2

9

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?

Poche answered 22/2, 2013 at 14:52 Comment(0)
I
9

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.

Innutrition answered 22/2, 2013 at 21:24 Comment(1)
running django 1.3, and although I have tried it I could not get this to work.Poche
K
0

How to do it in 2023?

format_html_lazy = lazy(format_html, str)

Works the same as format_html but keeps lazy translations lazy! :)

Kuwait answered 2/2, 2023 at 17:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.