Question

How can I create/handle dynamically forms, based on user content_type selection?

I'm writing a view/template for adding an object which model holds a generic key to other models:

 class MainModel(models.Model):
        title = models.CharField()
        author = models.ForeignKey(User)
...
        content_type = models.ForeignKey(ContentType)
        object_id = models.PositiveIntegerField()
        content_object = generic.GenericForeignKey('content_type', 'object_id')

class FileModel(models.Model):
    file = models.FileField()
    content = generic.GenericRelation(MainModel)


class UrlModel(models.Model):
    url = models.UrlField()
    content = generic.GenericRelation(MainModel)

I would like give the user a single page (for adding objects) where he/she could fill the title, author, ... fields and select the content_type (drop down list) and fill the fields of selected content_type e.g. file if FileModel was selected. This should be then send to a view with one "send" button, where proper objects of selected content_type and MainModels would be created. I am thinking of using some ajax/jquery to "expand" the initial form with fields from selected content_type but would welcome any other suggestions on how to do it right.

Was it helpful?

Solution

Just in case someone would benefit from this.

I ended up with 2 forms with different prefixes: 1) for the MainModel, 2) dynamically created for the selected content_type. The fields of form 2) are dynamically added to the site (on content_type selection) via ajax/jquery load function. The processing of the data & proper save are handled in the view.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top