简体   繁体   中英

How can I return image address to Django template from a function of the file views.py?

I need to display an image using Django templates but don't know how the "image address" will be returned from the function of the file views.py

The image address will be stored according to the " id " of the project (a project has an image associated with it).

Here is the function of the views.py file that I am writing:-

def file_path(request, awp_id):
    Component_Progress_Update_inst = get_object_or_404( Component_Progress_Update, pk=awp_id)
    filepath = Component_Progress_Update_inst.Supporting_documents.name
    filepath = "/media/"+filepath
    print(filepath)
    # Returning the file path
    return HttpResponse(filepath)

Following is the image tag , I am writing in HTML file:-

<img src="{% url 'component_progress:file_path' awp.id %}" alt="Supporting image" width="200" height="200">

But the image is not getting displayed, instead of the image this "alt text" is getting printed.

While I have tried displaying the image directly -> By directly writing that address in image " src ".

Maybe try: src="{{object.image.url}}"

With image.url you get the path of the image.

We just have to make changes in return line, it should be as follows:-

return HttpResponseRedirect(filepath)

It worked fine after using it !!

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