如何在django adminsite

问题描述

我想在Django管理站点上显示上载(通过FieldField)pdf文件。不显示pdf文件,而是自动下载。

同胞,我分享我正在尝试的代码:

models.py文件:

from django.db import models
from common.models import SubCategory,QuestionHistory

# Create your models here.

class BigotoBochor(models.Model):
    question_history = models.ForeignKey(QuestionHistory,on_delete=models.CASCADE)
    subcategory = models.ForeignKey(SubCategory,on_delete=models.CASCADE)
    pdf_file = models.FileField(upload_to='bigotobochor')

admin.py文件:

from django.contrib import admin
from .models import BigotoBochor
from django.utils.safestring import mark_safe

# Register your models here.

@admin.register(BigotoBochor)
class BigotoBochorAdmin(admin.ModelAdmin):
    list_display = ('question_history','subcategory','embed_pdf_file',)
    # list_editable = ('published',)
    list_filter = ('subcategory','question_history__board__name','question_history__year',)
    search_fields = ('question_history__year','question_history__board__name')
    list_per_page = 25


    # profile pic
    def embed_pdf_file(self,obj):
        if(obj.pdf_file != None and obj.pdf_file != "" ):
            return mark_safe('<embed src="{0}" type="application/pdf" width="50%" height="400px"/>'.format(obj.pdf_file.url,))
        
    embed_pdf_file.short_description = 'Question'

如何在adminsite中显示pdf文件?

解决方法

如果要在“ list_display”上显示pdf文件,只需

mvn test -Dsurefire.exitTimeout=40

将起作用。

,

在您的model.py中,您具有pdf_file,但您尝试在admin.py中显示embed_pdf_file。请参阅下面的修复

list_display = ('question_history','subcategory','pdf_file',)
,
from django.utils.html import format_html


class BookAdmin(admin.ModelAdmin):
    list_display = ('id','name','embed_pdf')

    def embed_pdf(self,obj):
        # check for valid URL and return if no valid URL
        url = obj.pdf_file.url
        html = '<embed src="{url}" type="application/pdf">'
        formatted_html = format_html(html.format(url=obj.cover.url))
        return formatted_html

这将在这样的浏览器中呈现pdf。

enter image description here

确保在Django设置中正确设置了X_FRAME_OPTIONS

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...