插入获取记录ID后如何在django admn?

时间:2012-05-13 09:23:13

标签: python django django-admin

我想在django admin中插入之后创建一个像记录ID这样的目录,我该怎样以及在哪里可以做到这一点。

我尝试使用save_model,但它不起作用,Gallery.ID返回None

型号:

class Gallery(models.Model):
    title = models.CharField(max_length=250)
    added = models.DateTimeField()
    active = models.BooleanField()

    def __unicode__(self):
        return self.title

和AdminModel

class GalleryAdmin(admin.ModelAdmin):
    save_on_top = True
    list_filter = ('active',)
    list_display = ('title','active','added')
    ordering = ['-added']
    inlines = [ImagesInline]

    def save_model(self, request, Gallery, form, change):
        if not change:
            Gallery.title = str(Gallery.id)
        Gallery.save()

2 个答案:

答案 0 :(得分:1)

将您的GalleryAdmin更改为此...在save()实例获取Gallery之前,您需要id

def save_model(self, request, Gallery, form, change):
    Gallery.save()
    if not change:
        Gallery.title = str(Gallery.id)

答案 1 :(得分:1)

def save_model(self, request, Gallery, form, change):
    if Gallery.id is None:
        Gallery.save()
    if not change:
        Gallery.title = str(Gallery.id)
    Gallery.save()

这将是第一次只做两个save()