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

Question:

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!.

Asked By: panchicore

||

Answers:

iPython or autocomplete is your best friend. Your problem is just that you are calling save on the Model itself. You need to call save on an instance.

ContentType.objects.latest('id').model_class()

some_ctype_model_instance = some_ctype.model_class()() 
some_ctype_model_instance.user = user
some_ctype_model_instance.save()

some_instance = some_ctype.model_class().create(...)

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()
Answered By: Blair