Skip to content Skip to sidebar Skip to footer

How Can I Have The Equivalent Of Django's Admin Inlines In A Modelform?

Django's admin allows you to easily create a form for editing a model and its foreign keys, but if I'm using a ModelForm in my own view, I'm having trouble accomplishing this. Here

Solution 1:

You can use inline formsets. From the documentation:

Suppose you have these two models:

from django.db import models

classAuthor(models.Model):
    name = models.CharField(max_length=100)

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

If you want to create a formset that allows you to edit books belonging to a particular author, you could do this:

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

The inlineformset_factory takes care of things behind the scenes, but for the front-end part you may find the django-dynamic-formset jQuery plugin useful.

Post a Comment for "How Can I Have The Equivalent Of Django's Admin Inlines In A Modelform?"