开发者

How to prevent Django from localizing IDs in templates?

I have recently upgraded to Django 1.2.5, and now I am having problems with localization, specifically number formatting. For example, in some templates I print the following samples:

data-id="{{ form.instance.id }}"

Which in cases >= 1000, used to evaluate to:

data-id="1235"

But now it actually results in (my localization is pt-BR, our decimal separator is dot):

data-id="1.235"

Which of c开发者_StackOverflow中文版ourse is not found when I afterwards query the database by ID. Using a |safe filter solves the problem, but I'm not willing to find all IDs in all templates and safe them.

Usually, I'll only localize the floating points, not the integers. I don't want to disable L10N, because of all the other formatting that is working fine. Is there a way to make this distinction in Django localization? Any other solution is accepted.


data-id="{{ form.instance.id|safe }}"

Also do the job


with django 1.2:

data-id="{{ form.instance.id|stringformat:'d' }}"

or, with django 1.3:

{% load l10n %}

{% localize off %}
    data-id="{{ form.instance.id|stringformat:'d' }}"
{% endlocalize %}

or (also with django 1.3):

data-id="{{ form.instance.id|unlocalize }}"
  • http://docs.djangoproject.com/en/1.3/topics/i18n/localization/#topic-l10n-templates
  • http://docs.djangoproject.com/en/1.3/ref/templates/builtins/#stringformat


This doesn't really answer your question but check out this section of the docs. It says to use {{ |unlocalize }} filter or:

{% localize on %}
    {{ value }}
{% endlocalize %}

{% localize off %}
    {{ value }}
{% endlocalize %}

There's probably a better way but I'm thinking that you could write a method that gives you the id as a string in your model for each model you are trying to display the id in a template.

class MyModel(models.Model):
    pass

    def str_id(self):
        return u'%s' % self.id

in your template:

{{ form.instance.str_id }}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜