简体   繁体   中英

readonly_fields returns empty value in django inlined models

i am new in django framework, in my current try, i have two models (Client and Facture). Facture is displayed as a TabularInline in client change view.

i want display a link for each inlined facture object to download the file. so i added a custom view that download the facture file, but dont know how to link to it

class Client(models.Model):
    ...

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

and in the 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)

i get the following error:

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

all works fine when i change the reverse url to

reverse("admin:clients_facture_change", args=[obj.pk])

so any one could help me know how to reverse the download view and if i am doing thinks right ?

thanks for any help

I would think you need to reverse the order in the url:

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

Firstly, you are using name='download' , but trying to reverse clients_facture_download .

I would try changing the url from

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

to

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

Secondly, InlineModelAdmin does not have a get_urls method. You should move it to your ClientAdmin class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM