Inlineformset with multiple models of the same type?

10 views
Skip to first unread message

sapp

unread,
Feb 25, 2014, 1:58:56 AM2/25/14
to django...@googlegroups.com
I'm trying to make a page that allows a user to edit/add many models at once. Let me give an example:


class SolarSystem(models.Model):
      name = models.CharField(...)
      description = models.CharField(...)

class Planet(models.Model):
      name = models.CharField(...)
      solarsystem = models.ForeignKey(SolarSystem)

I want the edit page to be something like:

SolarSystem 1
| -- Planet a form
| -- Planet b form
| -- Add new planet?

SolarSystem 2
| -- Planet c form
| -- Planet d form
| -- Planet e form
| -- Add new planet?

SolarSystem 3
| -- Planet f form
| -- Add new planet?

That is, it lists out the solar systems and allows the user to add new planets or edit an existing planet in a given solarsystem. In this example, SolarSystem 1
has planets a,b. The user can edit planet a,b. The user can also add a new planet to this solar system (Planet x, for example).

In my views, I can do something like:


def displayform(request): PlanetFormSet = inlineformset_factory(SolarSystem, Planet, extra=1) formset = PlanetFormSet(queryset=SolarSystem.objects.all()) return render_to_response(... {"formset":formset}, ...)

But I don't quite understand how the template should be written. The logic should be something like:

<form>
{% for solarsystem in solarsystems: %}
<span> Edit this solar system: {{ solarsystem.name }} </span>
{% for planetform in formset: %}
{{ form }}
</form>

The problem with that is how do I get solarsystem name from the formset and then group the planet's forms based on that solarsystem? How would Django know which
planetform goes with which solarsystem when I do a form post?

Reply all
Reply to author
Forward
0 new messages