简体   繁体   English

如何从文件views.py的function将图像地址返回到Django模板?

[英]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我需要使用Django 模板显示图像,但不知道如何从文件views.py的 function 返回“图像地址”

The image address will be stored according to the " id " of the project (a project has an image associated with it).图片地址将根据项目的“ id ”存储(一个项目有一个与之关联的图片)。

Here is the function of the views.py file that I am writing:-这是我正在编写的views.py文件的function:-

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:-以下是图像标签,我写在 HTML 文件中:-

<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 ".虽然我尝试直接显示图像 -> 通过直接在图像“ src ”中写入该地址。

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

With image.url you get the path of the image.使用 image.url 您可以获得图像的路径。

We just have to make changes in return line, it should be as follows:-我们只需要更改返回线,它应该如下:-

return HttpResponseRedirect(filepath)

It worked fine after using it !!使用后效果很好!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从模板文件夹中的ajax-html调用Django中views.py文件中的函数? - How make a call to a function in views.py file in Django from ajax-html in template folder? 如何在Django中从views.py重复调用函数? - How can I repeatedly call a function from a views.py in Django? 如何从 views.py 文件中导入 django 的 ChoiceField 中的所有选项? - how can i import all choices in a ChoiceField in django from the views.py file? 如果我不想返回任何东西,我可以在 Django Views.py function 中返回什么? - what can I return in Django Views.py function, if I dont want to return anything? 如何从views.py中的Django模板获取变量的值? - How to get value in variable from Django template in views.py? 在Django中,如何访问views.py中的模板值? - In Django, how do I access template values in the views.py? 使用 Django views.py 中另一个文件中的 function - Use function from another file in Django views.py 如何在Django的views.py文件中定义视图函数 - How to define a view function in views.py file in django 如何将在我的html文件上单击的图像的URL传递给views.py中的python函数 - how to pass the url of image clicked on my html file to my python function in views.py Django 我可以在 Django views.py 中从另一个 function 调用 function 吗? - Can I call an function from another function in Django views.py?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM