Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 895
panchicore Avatar asked Mar 22 '11 02:03

panchicore


People also ask

How do I get content type in Django?

The contenttypes framework is included in the default INSTALLED_APPS list created by django-admin startproject , but if you've removed it or if you manually set up your INSTALLED_APPS list, you can enable it by adding 'django. contrib. contenttypes' to your INSTALLED_APPS setting.

What is __ Str__ in Django model?

The __str__ method just tells Django what to print when it needs to print out an instance of the any model. It is also what lets your admin panel, go from this. Note: how objects are just plainly numbered. to this.

What is the class of instance object in Django?

The two main concepts of OOP are classes and objects: Class: Class is basically a blueprint or a template for creating objects. Object: Collection of arguments and methods which can be performed on those data. An object is nothing but an instance of the class.

How will you define the model classes in Django?

When you make a model class in Django, consider that class the data-table, each individual instance of that class the table rows, and the attributes(e.g: title) of each table the columns. In the definition of the class Book, title seems to be a class attribute.


1 Answers

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() 
like image 82
Blair Avatar answered Sep 18 '22 12:09

Blair