问题
Is there a way to get around python appending an "L" to Ints short of casting every time they come out of the database? (Note: I'm using Mysql)
OR, is there a way to ignore the L in django templates? (I keep getting invalid formatting errors because of this, but I'd rather not do list comprehension/casting EVERY time)
e.g. I have a dict with the object's pk as the key and I get the following in firebug:
invalid property id alert({183L: <Vote: colleen: 1 on Which best describes your wardrobe on any g...
Model: Question object, other attributes don't matter because the attribute in question is the pk
View: I didn't write the code and I can't follow it too well, so I can't post the section where the variable is being created, but it is a dict with Question pks as keys and Vote objects as values (code in question is from http://code.google.com/p/django-voting/wiki/RedditStyleVoting)
Template: {% votes_by_user user on questions as vote_dict %} to produce the dict in question alert({{vote_dict}}); is triggering the error
While in this particular case I'm just trying to alert the dict I got back, this has been a recurring problem for me when passing dicts or arrays into js functions where the function call fails because of the L. (Just to give you motivation behind the question)
回答1:
There's nothing wrong with Django here. However, it's going to be difficult to provide you with a relevant solution as we don't really know what you're trying to achieve.
Anyway, calling {{ vote_dict }} will call said dict's __str__ method, which is the common {key_repr:value_repr} pattern.
If you were to do the following:
{% for key, value in vote_dict.items %}
{{ key }} : {{ value }}
{% endfor %}
You'd get what you expect, without the L's.
On a sidenote, alert({{vote_dict}}) will almost always raise a JS error: alert's parameter is supposed to be a string.
Regarding Django - JS interoperability
If what you're trying to achieve is to pass Django items into JS funcitons seamlessly (which could indeed be possible with list instances), you could define a template filter that would return what you need.
For a list (or any kind of iterable that you'd want to represent as a list), you could use the following:
def js_list(iterable):
return '[%s]' % ', '.join(str(item) for item in iterable)
回答2:
Sounds like the meat of the problem here is that you want control over how the Django template language formats numbers before putting them into a HTTP response.
I would recommend using django.contrib.humanize, which provides template filters for this purpose.
See this question: Format numbers in django templates .
EDIT:
Realized that you are talking about iterables here. So a solution using the humanize filters would require you to loop through the iterable with a {% for %} {% endfor %} . Probably better to do it in the view as suggested in the first answer.
来源:https://stackoverflow.com/questions/9404142/how-to-get-python-to-not-append-l-to-longs-or-ignore-in-django-template