一尘不染

Django Admin嵌套内联

django

我需要一个嵌套的django admin内联,可以将date字段内联包含在另一个内联中,如下所示。

我有以下模型:

class Person(models.Model):
     name = models.CharField(max_length=200)
     id_no = models.IntegerField()

class Certificate(models.Model):
     cerfificate_no = models.CharField(max_length=200)
     certificate_date = models.DateField(max_length=100)
     person = models.ForeignKey(Person)
     training = models.CharField(max_length=200)

class Training_Date(models.Model):
      date = models.DateField()
      certificate = models.ForeignKey(Certificate)

和下面的管理员:

class CertificateInline(admin.StackedInline):
    model = Certificate

class PersonAdmin(admin.ModelAdmin):
     inlines = [CertificateInline,]
admin.site.register(Person,PersonAdmin)

但是我需要将Training_Date模型作为内联包含在内,这是证书管理内联的一部分。

任何想法 ?


阅读 957

收藏
2020-03-30

共2个答案

一尘不染

AFAIK,默认Django管理员中不能包含第二级内联。

Django admin只是一个普通的Django应用程序,因此没有什么可以阻止您实现第二级嵌套表单,但是恕我直言,这将是一种复杂的设计。也许这就是为什么没有规定的原因。

2020-03-30
一尘不染

解决此问题的一种常见方法是,通过同时具有同一模型的ModelAdmin和Inline,在第一和第二(或第二和第三)级别之间链接到admin:

使用TrainingDate作为内联,向证书提供ModelAdmin。给CertificateInline一个附加字段“详细信息”,该字段是其ModelAdmin更改表单的链接。

models.py:

from django.core import urlresolvers

class Certificate(models.Model):

    # ...

    def changeform_link(self):
        if self.id:
            # Replace "myapp" with the name of the app containing
            # your Certificate model:
            changeform_url = urlresolvers.reverse(
                'admin:myapp_certificate_change', args=(self.id,)
            )
            return u'<a href="%s" target="_blank">Details</a>' % changeform_url
        return u''
    changeform_link.allow_tags = True
    changeform_link.short_description = ''   # omit column header

admin.py:

# Certificate change form has training dates as inline

class TrainingDateInline(admin.StackedInline):
    model = TrainingDate

class CertificateAdmin(admin.ModelAdmin):
    inlines = [TrainingDateInline,]
admin.site.register(Certificate ,CertificateAdmin)

# Person has Certificates inline but rather
# than nesting inlines (not possible), shows a link to
# its own ModelAdmin's change form, for accessing TrainingDates:

class CertificateLinkInline(admin.TabularInline):
    model = Certificate
    # Whichever fields you want: (I usually use only a couple
    # needed to identify the entry)
    fields = ('cerfificate_no', 'certificate_date', 'changeform_link')
    readonly_fields = ('changeform_link', )

class PersonAdmin(admin.ModelAdmin):
    inlines = [CertificateLinkInline,]
admin.site.register(Person, PersonAdmin)
2020-03-30