python - How can I have the equivalent of django's admin inlines in a modelform? -
django's admin allows create form editing model , foreign keys, if i'm using modelform in own view, i'm having trouble accomplishing this. here's example in admin.py:
class vendorphotoinline(admin.stackedinline): model = vendorphoto = 3 class vendoradmin(admin.modeladmin): inlines = [vendorphotoinline] admin.site.register(vendor, vendoradmin)
so in admin, can create vendor , add bunch of photos. non-staff, have form creating vendor, , i'd allow them upload photos admin.
i'm using modelform allows users create new vendors, of course, can't add photos @ point:
class vendorform(modelform): class meta: model = vendor
how can achieve parity admin interface here? i'd settle solution works new vendor instances , allows uploading of number (say, 3), works existing instances , allows adding / deleting photos great too. help!
you can use inline formsets. documentation:
suppose have these 2 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 want create formset allows edit books belonging particular author, this:
>>> 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 scenes, front-end part may find django-dynamic-formset jquery plugin useful.
Comments
Post a Comment