Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python gettext error: Can't convert '__proxy__' object to str implicitly

I'm suddenly getting a weird error in code that was previously working. I recently upgraded to Django 1.9.6 from 1.9.4.

In one of my views, I have:

from django.contrib import messages
from django.utils.translation import ugettext_lazy as _

messages.success(request, str( _('A string with a ') +
    '<a target="_blank" href="/preview/' + mymodel.hash + '">' +
    _('link!') + '</a>.'), extra_tags="safehtml"
    )

This now gives a TypeError on the 2nd last line:

Can't convert '__proxy__' object to str implicitly

Why? How do I fix this?

Edit:

This can be fixed by wrapping the second call to ugettext_lazy() in str() (i.e. the code becomes str( _('link!') ). Doing this allows the view to render fine. My questions is hence now: Why? The entire composite string is already wrapped in str(), and as I said, this code worked fine with the previous version of django. Is this a bug?

like image 391
Escher Avatar asked May 24 '16 09:05

Escher


2 Answers

__proxy__ is translation string whose actual translation result isn’t determined until the object is used in a string (i.e. what happens when you use ugettext_lazy instead of ugettext here).

Documentation

like image 148
Escher Avatar answered Nov 03 '22 05:11

Escher


According to the given Documentation link:

Calling str() with the lazy translation as the argument will generate a string in the current locale.

like image 4
Antonio Romero Oca Avatar answered Nov 03 '22 05:11

Antonio Romero Oca