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

Time:12-22

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

CodePudding user response:

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

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

CodePudding user response:

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

return HttpResponseRedirect(filepath)

It worked fine after using it !!

  • Related