On 6 fév, 08:01, Saurav <prio...@gmail.com> wrote:
> Hi,
>
> I want to know if its possible to convert a string object into class
> object.

I assume you mean "retrieve an existing class object by it's name".

(snip)

> http://dpaste.com/117323/
>
> at line no 40,

f = model_name.__name__+"Form"(instance=a)

Won't work - str is not a callable type.

> if you notice, I m trying to add "Form" to the
> model_name for creating an instance of the class CompanyForm, here is
> my problem, as a result of the addition it becomes string object

Given that you are concatening two strings, you could hardly expect
anything else than a string.


Ok - first point, at line 33, you have:

 # nb : until this point 'model_name' is a str
 model_name = get_model('dashboard',model_name)


get_model returns a class object (a Model subclass FWIW). Naming it
"model_name" is a *very* poor choice. Name it 'model', or 'model_cls',
or 'model_object', but please leave the original model_name alone.


Now wrt/ your question: you can retrieve an object's attribute by name
using the getattr(obj, name) function. Since module are objects and
class objects are (usually) attributes of their module, if module
"somemodule" defines class "SomeClass", you can do:

import somemodule
someclass = getattr(somemodule, "SomeClass")

Also, if the object to retrieve by name actually lives in the current
namespace, you can also retrieve it using a dict returned by globals()
or locals(). In your case, since CompanyForm is defined in the same
module, this is what you want.

class Foo(object):
    pass


def bar():
   cls = globals()['Foo']


> and
> hence im getting the error 'str' object is not callable'

Obviously, yes.

> How can I overcome this problem ??

cf above.

Also, taking time to learn Python (and eventually asking Python-
related question in a Python-related newsgroup - like, for example,
comp.lang.python) might be a good idea...

HTH
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to