Django 2将自定义按钮添加到管理员

时间:2018-12-19 09:36:55

标签: django

使用Django 2.1.4,其管理网站和ModelAdmin。

我想在模型列表中的每个项目附近添加一个自定义按钮,如图所示。

单击按钮应打开一个自定义视图。

为此,我在ModelAdmin中添加了一个网址。

问题是,当单击“生成预览”按钮时,未调用该视图,而是收到一条错误消息,即ID为“ 419 / gen_pdf_preview”的“ Questionario istituzione scolastica”不存在。被删除了吗?”。

Django的

http日志针对请求报告了代码302:

[19/Dec/2018 09:16:54] "GET /en/admin/vision/questionarioistituzionescolastica/419/gen_pdf_preview/ HTTP/1.1" 302 0 
[19/Dec/2018 09:16:55] "GET /en/admin/vision/questionarioistituzionescolastica/419/gen_pdf_preview/change/ HTTP/1.1" 302 0

我尝试了两种方法,但两种方法都无效:

1-扩展的ModelAdmin内部的视图

2-外部视图

这是来自admin.py的自定义ModelAdmin:

from .models import * 
from .views import serve_pdf_preview 
from django.utils.html import format_html

@admin.register(QuestionarioIstituzioneScolastica) 
class QuestionarioIstituzioneScolasticaAdmin(admin.ModelAdmin):

    list_display = ('denominazione_istituzione_scolastica', 'generate_pdf_preview_html')

    def generate_pdf_preview_html(self, obj):
        return format_html('<a class="button" href="%s/gen_pdf_preview/">Generate preview</a>' % obj.id)

    generate_pdf_preview_html.short_description = 'Generate pdf preview'
    generate_pdf_preview_html.allow_tags = True

    def get_urls(self):
        from django.urls import path

        urls = super().get_urls()
        urls += [
            # path('<path:object_id>/gen_pdf_preview/', self.admin_site.admin_view(self.generatepdf_view), name='vision_questionarioistituzionescolastica_generatepdf')
            path('<path:object_id>/gen_pdf_preview/', self.admin_site.admin_view(serve_pdf_preview),
                 name='vision_questionarioistituzionescolastica_generatepdf')
        ]

        for u in urls:
            print(u)

        return urls

    # also tried this way, but it does not work either
    def generatepdf_view(self, request, object_id, form_url='', extra_context=None):
        print("generatepdf_view {0}".format(str(object_id)))
        pass

外部视图很简单:

def serve_pdf_preview(request, id):
    print("views.serve_pdf_preview")
    return HttpResponse("pdf render")

及其urlpattern:

urlpatterns = [
   ...
   path('<int:pk>/gen_pdf_preview/', views.serve_pdf_preview)
   ...

任何线索?

enter image description here

1 个答案:

答案 0 :(得分:2)

一切似乎都很好,只需在get_urls方法中将自定义网址附加到管理网址之前,即可:

urls = super().get_urls()
custom_urls  += [
        # path('<path:object_id>/gen_pdf_preview/', self.admin_site.admin_view(self.generatepdf_view), name='vision_questionarioistituzionescolastica_generatepdf')
        path('<path:object_id>/gen_pdf_preview/', self.admin_site.admin_view(serve_pdf_preview),
             name='vision_questionarioistituzionescolastica_generatepdf')
    ]

return custom_urls + urls