views:

301

answers:

2

I'm having trouble with sending localized messages to Django users using the

user.message_set.create(message="Message")

mechanism. First of all,

user.message_set.create(message=_("Message"))

flat out doesn't work, SQLite says it won't accept the non-ascii parameter (localized message contains special characters).

user.message_set.create(message=unicode(_("Message")))

sends the original English message regardless of the preferred language (other translated parts of the app do work correctly).

Using a hardcoded localized message like this

user.message_set.create(message=u"Localized message áýčš")

is the only thing that works but that implies that I'd be able to only use one language.

How can I send users localized messages loaded from LC_MESSAGES?

+1  A: 

Have you tried localizing the message right before you display it?

In your view:

user.message_set.create(message="Message")

In your template

{% if messages %}
<ul>
    {% for message in messages %}
    <li>{% trans message %}</li>
    {% endfor %}
</ul>
{% endif %}

This way, you don't have to store any odd characters in your database.

scompt.com
theres's one problem with this. I'm guessing that 'makemessages' command won't catch the string and you'll have to remember to edit django.po file manually, or use a workaround - add a dummy line with _("Message") in the .py code
Evgeny
+1  A: 
user.message_set.create(message=_("Message"))

... should work. Are you using the latest version of SQLite, does UTF-8 support have to be enabled somehow? Are you storing non-ascii characters in SQLite elsewhere?

Emil Stenström
I'm not using the latest SQLite since the CentOS setup I have wouldn't support it. But I definitely do store non-ascii characters elsewhere in the database.
TomA
That's what's suprising to me - most stuff works, it's just the message system that doesn't.
TomA
Could it be that in the context you're in, _ is not aliased properly to ugettext? http://docs.djangoproject.com/en/dev/topics/i18n/#s-standard-translation
Emil Stenström
Nope, _ is aliased and works correctly a few lines below for other stuff.
TomA