django content types - how to get model class of content type to create a instance?

panchicore picture panchicore · Mar 22, 2011 · Viewed 19.6k times · Source

I dont know if im clear with the title quiestion, what I want to do is the next case:

>>> from django.contrib.contenttypes.models import ContentType
>>> ct = ContentType.objects.get(model='user')
>>> ct.model_class()
<class 'django.contrib.auth.models.User'>
>>> ct_class = ct.model_class()
>>> ct_class.username = 'hellow'
>>> ct_class.save()
TypeError: unbound method save() must be called with User instance as first argument        (got nothing instead)

I just want to instantiate any models that I get via content types. After that I need to do something like form = create_form_from_model(ct_class) and get this model form ready to use.

Thank you in advance!.

Answer

Blair picture Blair · Mar 22, 2011

You need to create an instance of the class. ct.model_class() returns the class, not an instance of it. Try the following:

>>> from django.contrib.contenttypes.models import ContentType
>>> ct = ContentType.objects.get(model='user')
>>> ct_class = ct.model_class()
>>> ct_instance = ct_class()
>>> ct_instance.username = 'hellow'
>>> ct_instance.save()