Thursday, July 2, 2015

Re: Creating model (table) inheritance in Django 1.8 using PostgreSQL

You could dynamically create a ModelForm based on the model class:

from django.forms import ModelForm

MetaClass = type('Meta', (), {'model': ProductItemText})

MetaModelForm = type('ProductModelForm', (ModelForm, ), {'Meta': MetaClass})

form = MetaModelForm()

The only thing you would need is the model class itself ("ProductItemText" in this particular case),  I think you could even add it as a classmethod to the base Product class.





On Thu, Jul 2, 2015 at 9:34 AM, Some Developer <someukdeveloper@gmail.com> wrote:
I have a model which defines an item and many sub-models which inherit from it to define the type of the model. Something like this:

Product(models.Model):
        owner = models.ForeignKey(settings.AUTH_USER_MODEL)
        name = models.CharField(max_length=255)

ProductItemText(Product):
        type = models.TextField()

ProductItemBoolean(Product):
        type = models.BooleanField()

etc etc. There are a lot more different sub-models for different types.

I'm a bit confused about how to generate a form based on the type that the user wants to add to the database. Do you have to have a form each individual sub-type or is there a nice workaround for this specific problem?

Any help is appreciated.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/55952FDF.8000604%40googlemail.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CALn3ei2Cgh_nmmvJrKgzCcErRaKEQ5L6PJcPGA%2Bwch07bk2mag%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment