Wednesday, September 16, 2015

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

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?

--
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/CALHvOW5BWkFGCvdMwZm36%2BK4A06iG7S27%3DyqreDR6Zc%3DBP-dNg%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment