简体   繁体   中英

Django: Template Tag unable to load image.Only reading media image

I am trying to generate a PDF with django pisa module.

views.py

def reportPdf(template_src, context_dict):

        template = get_template(template_src)
        context = Context(context_dict)
        htmlRender = template.render(context)
        resultObj = StringIO.StringIO()
        pdfObject = pisa.pisaDocument(StringIO.StringIO(htmlRender.encode(
            'utf-8')), resultObj,link_callback=fetch_resources)
        response = HttpResponse(resultObj.getvalue(), content_type = 'application/pdf')
        response["Content-Disposition"] = 'inline;filename=sample.PDF'
        return response
 def fetch_resources(uri, rel):
         import project.settings
         path = os.path.join(project.settings.MEDIA_ROOT, uri.replace(
                                            project.settings.MEDIA_URL, ""))
         return path

class abc():
     def get(self,request, *args, **kwargs):
     // some code
     return reportPdf('pdf.djhtml',{'pagesize': 'A4',"refer_data":detail}

settings.py:

PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
MEDIA_ROOT = os.path.realpath(os.path.join(PROJECT_PATH, "media"))
MEDIA_URL = '/media/'

Template:

pdf.djhtml: code for image available in media folder:

<img src="/media/sample.jpg"/>

Above works fine as i have incorporated media in views.py

But below code doesn't load the image.

refer_data.image.url = http://www.w3schools.com/images/w3schools_green.jpg (Consider this http url as sample for testing).This Image url I am getting from a API call.

 {% if refer_data.image.url != "" %}
        <img src="{{refer_data.image.url}}"/>
 {% else %}
       <img src="noimage.png"/>

 {% endif %}

Could someone analyse and share some idea where I am missing? Any help will be appreciated.

You could check if you are dealing with a local or absolute HTTP URL in fetch_resources , an example using the validator package:

import project.settings
import validators

def fetch_resources(uri, rel):
    if validators.url(uri):
      return uri
    else:
      path = os.path.join(project.settings.MEDIA_ROOT, uri.replace(
                                            project.settings.MEDIA_URL, ""))
      return path

For an absolute url ( http://www.google.com ) return the url else for a relative url /media/myimage.jpg it returns the joined media path.

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