Neo
Neo

Reputation: 13881

Python : convert unicode string to raw object/text

I've got a set of key, value pairs dictionary in my Django application. The value in the dictionary is a string type.

{u'question': u'forms.CharField(max_length=512)'}

I need to convert this "value" string to an actual object, and get something like this.

properties = {
    'question' : forms.CharField(max_lenth=512)
    }

Notice that values in the second dictionary are actual Django form fields and NOT strings. I need to do this manipulation to create dynamic forms. The second dictionary is to be passed to "type" built-in function. Sample code can be found on this page. http://dougalmatthews.com/articles/2009/dec/16/nicer-dynamic-forms-django/ .

Upvotes: 0

Views: 1596

Answers (3)

Marcelo Cantos
Marcelo Cantos

Reputation: 185842

EDIT: Based on clarifying comments by the OP, this isn't an appropriate solution.


I don't know the constraints you are under, but perhaps the following representation will work better:

{u'question': lambda: forms.CharField(max_length=512)}

You can then "realise" the fields thus:

dict((k, v()) for (k, v) in props.iteritems())

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798546

If you modify your representation a bit:

fields = {u'question': u'{"field": "django.forms.CharField", "params": {"max_length": 512}}'}

then you can use the following:

from django.utils import importlib, simplejson

def get_field(fname):
  module, name = fname.rsplit('.', 1)
  return getattr(importlib.import_module(module), name)

print dict((k.encode('ascii', 'ignore'), get_field(v['field'])(**v['params']))
  for k, v in ((k, simplejson.loads(v)) for k, v in fields.iteritems()))

Upvotes: 3

Don
Don

Reputation: 17606

Following your code, I suggest to separate field name from field attrs:

my_fields = {u'question': {'name': 'CharField', 'attrs': {'max_length': 512} }} 

and then something like:

properties = {}
for field_name, field_def in my_fields.items():
    properties[field_name] = getattr(forms, field_def['name'])(**field_def['attrs'])

Upvotes: 1

Related Questions