0

In the code below I render the person model. Instead of person() I want to use a getattr to make use of a variable model name. Something like getattr('person', ????) The code below is a simplified verdion of my app engine code.

class person(djangoforms.ModelForm):

    name = djangoforms.forms.CharField(max_length=24, min_length=2, label = 'Name', required = True)


class MainPage(webapp.RequestHandler):

    def get(self):

    path = os.path.join(os.path.dirname(__file__), 'templates', 'person.html')
    self.response.out.write(template.render(path, {'form' : person(), 'name' : 'voscausa'}))
voscausa
  • 11,253
  • 2
  • 39
  • 67
  • Yes, I was looking for somtehing like that. I have already tried the '__init__'. It returns an error: ERROR 2011-03-24 14:45:26,290 __init__.py:395] 'method-wrapper' object is not iterable – voscausa Mar 24 '11 at 14:52

3 Answers3

0

The constructor of a python class is named __init__, so use getattr(YourClass, '__init__').

However, this is probably not what you want. See Does python have an equivalent to Java Class.forName()? - this might be the solution for your question.

Community
  • 1
  • 1
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • I have tried to implement the second part of your answer. adding the the function you suggested : def get_class( kls ): parts = kls.split('.') module = ".".join(parts[:-1]) m = __import__( module ) for comp in parts[1:]: m = getattr(m, comp) return m But this gives : TypeError: 'ModelFormMetaclass' object is not iterable – voscausa Mar 24 '11 at 15:03
0

I used

get_class('main.person')()

instead of

get_class('main.person')

to get

self.response.out.write(template.render(path, {'form' : get_class('main.person')(), 'name' : 'voscausa'}))
worldofjr
  • 3,868
  • 8
  • 37
  • 49
voscausa
  • 11,253
  • 2
  • 39
  • 67
0
try:
    globals()[model_name]()
except KeyError:
    print "hey, you forgot to define %s"%model_name
vartec
  • 131,205
  • 36
  • 218
  • 244