How to create a Django formset with three or more related items?

21 views
Skip to first unread message

John Schmitt

unread,
Sep 16, 2015, 2:24:12 PM9/16/15
to django...@googlegroups.com

I posted this question on SO, perhaps someone can answer it. http://stackoverflow.com/questions/32615421/

This Django doc explains inline formsets, and uses this nice example:

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    author = models.ForeignKey(Author)
    title = models.CharField(max_length=100)

>>> from django.forms.models import inlineformset_factory
>>> BookFormSet = inlineformset_factory(Author, Book, fields=('title',))
>>> author = Author.objects.get(name='Mike Royko')
>>> formset = BookFormSet(instance=author)

Now, if I add a third model:

class Event(models.Model):
    author = models.ForeignKey(Author)
    location = model.CharField(max_length=100)

How do I create a formset that allows me to edit all three models? Suppose there were even more models with a ForeignKey to Author, how do I create a formset for that? For example,

class Store(models.Model):
    author = models.ForeignKey(Author)
    store = model.CharField(max_length=100)

There are now three related objects to Author. How do I create a formset for all four objects?

Reply all
Reply to author
Forward
0 new messages