readonly_fields returns Django 内联模型中的空值

readonly_fields returns empty value in django inlined models

我是 django 框架的新手,在我目前的尝试中,我有两个模型(Client 和 Facture)。 Facture 在客户端更改视图中显示为 TabularInline。

我想为每个内联的 facture 对象显示一个 link 以下载文件。所以我添加了一个自定义视图来下载 facture 文件,但不知道如何 link

class Client(models.Model):
    ...

class Facture(models.Model):
    client = models.ForeignKey(Client, on_delete=models.CASCADE)
    numero = models.IntegerField(unique=True, default=rand_code)
    ...

并在 admin.py 中:

class FactureInline(admin.TabularInline):

    model = Facture
    extra = 0

    readonly_fields = ('numero', 'dl_link')

    def DLFacture(self, request, obj):
        ...
        response.write(pdf)
        return response

    def get_urls(self):
        urls = super(FactureAdmin, self).get_urls()
        from django.conf.urls import url
        download_url = [
            url(r'^(?P<pk>\d+)/download/$', self.admin_site.admin_view(self.DLFacture), name="download"),
        ]
        return download_url + urls

    def dl_link(self, obj):
        from django.core.urlresolvers import reverse
        return reverse("admin:clients_facture_download", args=[obj.pk])

admin.site.register(Facture, FactureAdmin)

class ClientAdmin(admin.ModelAdmin):
    inlines = [
        FactureInline,
    ]
admin.site.register(Client, ClientAdmin)

我收到以下错误:

Reverse for 'clients_facture_download' with arguments '(1,)' and keyword arguments '{}' not found. 0 pattern(s) tried: []

当我将反向 url 更改为

时一切正常
reverse("admin:clients_facture_change", args=[obj.pk])

所以任何人都可以帮助我知道如何反转下载视图以及我是否认为正确?

感谢您的帮助

我认为您需要颠倒 url 中的顺序:

url(r'^download/(?P<pk>\d+)$', self.admin_site.admin_view(self.DLFacture), name="download"),
    ]

首先,您正在使用 name='download',但试图反转 clients_facture_download

我会尝试将 url 从

更改为
url(r'^(?P<pk>\d+)/download/$', self.admin_site.admin_view(self.DLFacture), name="download"),

url(r'^(?P<pk>\d+)/download/$', self.admin_site.admin_view(self.DLFacture), name="clients_fracture_download"),

其次,InlineModelAdmindoes not have一个get_urls方法。你应该把它移到你的 ClientAdmin class.