如何在模型形式中具有与django的admin内联等效的功能? [英] How can I have the equivalent of django's admin inlines in a modelform?

查看:47
本文介绍了如何在模型形式中具有与django的admin内联等效的功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Django的管理员允许您轻松创建用于编辑模型及其外键的表单,但是如果我在自己的视图中使用ModelForm,则很难做到这一点.这是admin.py中的示例:

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.

我正在使用允许用户创建新供应商的ModelForm,但是,当然,他们目前不能添加照片:

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

如何在此处与管理界面实现同等?我会选择一个仅适用于新的Vendor实例并允许上传最多一定数量(例如3)的解决方案,但是某些适用于现有实例并允许添加/删除照片的解决方案也将很棒.感谢您的帮助!

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!

推荐答案

您可以使用内嵌表单集.从文档中:

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)

inlineformset_factory 负责幕后工作,但对于前端部分,您可能会找到

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.

这篇关于如何在模型形式中具有与django的admin内联等效的功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆