开发者

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

开发者 https://www.devze.com 2023-02-18 02:21 出处:网络
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

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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消