djangoimagedjango-templatespisa

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.


Solution

  • 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.