将模板导出为PDF时未显示Django图像

时间:2019-02-27 10:40:56

标签: django python-2.7

我一直在寻找并尝试解决此问题的许多解决方案(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和django DetailView。在模板中,我尝试按以下方式呈现模型的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),但没有结果。有人对此问题有可行的解决方案吗?

1 个答案:

答案 0 :(得分:0)

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

  • 添加一种方法来获取模型中图像的路径

    def get_image_path(self):
        if image:
            return os.path.join(settings.MEDIA_ROOT, self.image.path)
        return ''
    
  • file://插入模板中的路径

    <img src="file://{{ obj.get_image_path }}">