0

Is there any template tag or workaround in django to make ast.literal_eval(some_str) in a template?

shoud I create a new template tag to do that? In this case, how would be that template tag?

The reason why I'm asking can be found here how to deserialize a python printed dictionary?

Community
  • 1
  • 1
jperelli
  • 6,988
  • 5
  • 50
  • 85

1 Answers1

4

No

Why would there be such a specific tag and why it would be used?

You can add one easily

# file: literal_eval.py

import ast

def literal_eval(value):
    return ast.literal_eval(value)

from django import template
register = template.Library()
register.filter('literal_eval', literal_eval)

and you can use it like this in template

{% load literal_eval %}

{{ some_str|literal_eval }}

now that leads to the question "Why?" what you will do with this?

Edit: OP said "he wants to deserialize some python dict saved as varchar", in that case template is not the place to do it, first convert text to dict and then pass it to template.

and better still rethink what is being done, saving dict repr is not the way to serialize and using literal_eval is not the way to de-serialize dicts, use json.dumps or such format to put dict into database and use json.loads to convert it back to dict. You can use pickle also but I would not recommend it.

jperelli
  • 6,988
  • 5
  • 50
  • 85
Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
  • asked your question in my question – jperelli Oct 31 '12 at 18:57
  • sorry, I said something stupid :) This is the reason: http://stackoverflow.com/questions/13165479/how-to-deserialize-a-python-printed-dictionary – jperelli Oct 31 '12 at 19:01
  • 2
    @jperelli you are not doing it the right way, you should not be doing this in template – Anurag Uniyal Oct 31 '12 at 19:02
  • Ok, thank you all. I'm just working with this database, and this is how the data was stored (it's awful, but I received like that, and have to work with it). I'll try to "refactor" the data in order to be JSON or BSON. – jperelli Oct 31 '12 at 19:15