将多条记录添加到django admin中

时间:2014-05-01 05:06:44

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

我希望能够在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)

截图: django admin panel

有没有办法我可以在1个屏幕上一次说5个,这是非常缓慢地填充1乘1.我可以在mysql中使用SQL查询,但我想在这里实现这一点。

由于

1 个答案:

答案 0 :(得分:0)

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

以下是您必须做的事情:

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

  2. 您会在添加照片管理页面上看到表单集,并且应该可以正常运行。如果您没有,则可以通过在管理中提供add_form_templatechange_form_template 属性来覆盖模板,并显示该表单模板。

  3. 处理保存Formset中的多个对象

  4. 例如:

    ### admin.py ###
    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"
    
    admin.site.register(Photo, PhotoAdmin)
    

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