[Django]-Django content types – how to get model class of content type to create a instance?

59👍

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()
👤Blair

8👍

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(...)

Leave a comment