【问题标题】:Django images NOT showing when exporting template as PDF将模板导出为 PDF 时不显示 Django 图像
【发布时间】:2019-07-21 01:29:34
【问题描述】:

我一直在寻找并尝试解决这个问题的一些解决方案(herehere 等等),但我仍然无法解决这个问题。

所以,我使用PDFViewMixin 将模板导出为 PDF:

from django.views.generic.detail import TemplateResponseMixin

class ExportViewMixin(TemplateResponseMixin):
    filename = None
    content_type = 'text/html'

    def get_filename(self):
        return self.filename

    def get_content_type(self):
        return self.content_type

    def document_to_response(self, response, context=None):
        raise NotImplementedError('Subclasses must implement this method')

    def render_to_response(self, context, **kwargs):
        response = HttpResponse(content_type=self.get_content_type())
        response['Content-Disposition'] = 'attachment;filename="%s"' % self.get_filename()
        self.document_to_response(response, context=context)
        return response

 class PDFViewMixin(ExportViewMixin):
   '''Generic view that render a template into a PDF 
   and return it as response content.
   '''
   content_type = 'application/pdf'

   def gen_pdf(self, context):
       template = get_template(self.template_name)
       # need absolute_uris to correctly get static files
       try:
           html_doc = HTML(string=template.render(Context(context)), base_url=context.get('base_url'))
       except TypeError:       # Django>=1.11
           html_doc = HTML(string=template.render(context), base_url=context.get('base_url'))
       return html_doc.render()

   def document_to_response(self, response, context=None):
       self.gen_pdf(context).write_pdf(response)

   def get_context_data(self, **context):
       context = super(PDFViewMixin, self).get_context_data(**context)
       context['base_url'] = self.request.build_absolute_uri()
       context['content_type'] = self.get_content_type()
       return context

控制模板的视图继承自PDFViewMixin和djangoDetailView。在模板中,我尝试如下渲染模型的ImageField(在导出之前完美运行):

{% if object.image %}
   <img src="{{ object.image.url }}">
{% endif %}

我相信(正如 here 指出的那样)问题在于 render_to_response 的行为类似于 AnonymousUser,而白色它试图通过登录获取图像,但出现错误。确实,这是我在控制台中得到的请求日志:

[27/Feb/2019 11:05:10] "GET /login/?next=/media/images/0013/765-default-avatar.png HTTP/1.1" 200 3379
WARNING: Failed to load image at "http://localhost:8000/media/images/0013/765-default-avatar.png" (Pixbuf error: Unrecognized image file format)

我尝试使用绝对 uri 设置自定义 photo_url_fetcher(如 this),但没有结果。有人对此问题有有效的解决方案吗?

【问题讨论】:

    标签: django python-2.7


    【解决方案1】:

    经过各种尝试,我找到了这个解决方案:

    • 添加获取模型中图片路径的方法

      def get_image_path(self):
          if image:
              return os.path.join(settings.MEDIA_ROOT, self.image.path)
          return ''
      
    • 在模板路径前添加file://

      &lt;img src="file://{{ obj.get_image_path }}"&gt;

    【讨论】:

      猜你喜欢
      • 2016-12-13
      • 1970-01-01
      • 2013-02-16
      • 1970-01-01
      • 1970-01-01
      • 2020-05-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多