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

2

35

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

Mocha answered 22/3, 2011 at 2:33 Comment(0)
D
60

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()
Duthie answered 22/3, 2011 at 2:38 Comment(2)
cool!, and if I want to make querysets: ct_instance.__class__.objects.all() - with this I can use the formset factory to create dynamic forms of all instances I need. thanks!Mocha
You could also get the queryset directly from the class - ct_class.objects.all().Duthie
D
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(...)
Deoxidize answered 22/3, 2011 at 2:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.