【问题标题】:Adding multiple records into django admin将多条记录添加到 django admin
【发布时间】:2014-06-17 14:44:51
【问题描述】:

我希望能够在 django admin 中一次添加多条记录。

models.py

class Photo(models.Model):
    pub_date = models.DateTimeField('date published')
    sort = models.IntegerField()
    photo_category = models.ForeignKey(Photocategory)
    title = models.CharField(max_length=200)
    title_url = models.SlugField(max_length=200)
    main_image = models.ImageField(blank=True, null=True, upload_to='images/photo/')
    # size is "width x height"
    cropping = ImageRatioField('main_image', '350x350')

    def image_thumbnail(self):
       return '<a href="/media/%s" target="_blank"><img width="160px" src="/media/%s"/></a>' % (self.main_image, self.main_image)

    image_thumbnail.allow_tags = True
    image_thumbnail.short_description = 'main_image'

    def __unicode__(self):
        return self.title

admin.py

class PhotoAdmin(ImageCroppingMixin, admin.ModelAdmin):

    prepopulated_fields = {'title_url': ('title',)}
    list_display = ('title', 'photo_category', 'image_thumbnail', 'sort')
    list_filter = ['photo_category']
    admin.site.register(Photo, PhotoAdmin)

截图:

有没有一种方法可以让我在 1 个屏幕上一次说 5 个,1 个 1 的填充非常慢。我可以在 mysql 中使用 SQL 查询来完成,但我想在这里实现这一点。

谢谢

【问题讨论】:

    标签: django django-models django-admin django-views multiple-entries


    【解决方案1】:

    嘿是的这是可能的,但开箱即用,,

    这是你必须做的:

    1. 在 PhotoAdmin 的form 属性中定义一个Formset(创建多个照片表单)

    2. 您将在添加照片管理页面上看到一个表单集,并且应该可以正常工作。如果您不这样做,那么您可以通过在管理中提供add_form_templatechange_form_template 属性 来覆盖模板并显示该表单集模板。

    3. 处理在表单集中保存多个对象

    例如:

    # admin.py
    
    @admin.register(Photo)
    class PhotoAdmin(ImageCroppingMixin, admin.ModelAdmin):
        prepopulated_fields = {'title_url': ('title',)}
        list_display = ('title', 'photo_category', 'image_thumbnail', 'sort')
        list_filter = ['photo_category']
            
        form = MyFormset
        add_form_template = "photo/admin/my_add_form.html"
        change_form_template = "photo/admin/my_change_form.html"
    

    这是一个粗略的工作流程,您必须尝试并在需要时进行修改。 你可以参考这个文档:https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#modeladmin-options

    【讨论】:

    • 有没有办法发布一个小例子来做到这一点?我在 django 方面不是那么先进,它可以是一个小的工作示例。谢谢
    • 如果您可以阅读有关在 Django 中使用 Formsets 的信息,对您的学习会更好。我可以提供阅读链接:docs.djangoproject.com/en/1.6/topics/forms/formsets 它将帮助您更快地学习
    • 这个答案其实是不正确的。如果要添加,一次编辑多个对象,请查看 django-bulk-admin github.com/purelabs/django-bulk-admin
    猜你喜欢
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-12
    • 2011-03-28
    • 2018-10-13
    • 1970-01-01
    • 2017-04-09
    相关资源
    最近更新 更多