mrooney
mrooney

Reputation: 2022

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's an example in admin.py:

class VendorPhotoInline(admin.StackedInline):
  model = VendorPhoto
  extra = 3

class VendorAdmin(admin.ModelAdmin):
  inlines = [VendorPhotoInline]

admin.site.register(Vendor, VendorAdmin)

So now in the admin, I can create a Vendor and add a bunch of photos. However for non-staff, I have a form for creating a Vendor, and I'd like to allow them to upload some photos like the admin.

I'm using a ModelForm that allows users to create new Vendors, but of course, they can't add photos at this point:

class VendorForm(ModelForm):
    class Meta:
        model = Vendor

How can I achieve parity with the admin interface here? I'd settle for a solution that just works for new Vendor instances and allows uploading of up to a certain number (say, 3), but something that works for existing instances and allows adding / deleting photos would be great too. Thanks for any help!

Upvotes: 2

Views: 1059

Answers (1)

Paulo Almeida
Paulo Almeida

Reputation: 8071

You can use inline formsets. From the documentation:

Suppose you have these two models:

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)

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.

Upvotes: 2

Related Questions