【问题标题】:How to send an image from dir in django如何从 django 中的 dir 发送图像
【发布时间】:2019-11-30 14:43:14
【问题描述】:

我想为像 /favicon.ico 这样的网站图标添加一个网址。我的图片位于 static/graphics/images/favicon.ico。我不想重定向。我试过了:-

from django.contrib import admin
from django.urls import path, include
from search import views
from django.views.generic.base import RedirectView
faviconI=RedirectView.as_view(url='/static/gr/favicon.ico')
urlpatterns = [
    path('', views.Page, name='Home'),
    path('favicon.ico/', faviconI, name="favicon")
]

但代码给出了重定向。我想从目录加载图像而不重定向。

【问题讨论】:

  • >您可以查看 stackoverflow.com/questions/1156246/… 并查看 Cory 建议使用 serve 的答案。所以你必须创建一个在 urlpatterns 中引用的视图函数/类。视图函数调用如 Cory 的回答中所述

标签: python django django-urls


【解决方案1】:

您可以使用 django smart_str 方法从目录发送图像。

from django.utils.encoding import smart_str
response = HttpResponse(mimetype='application/force-download')    
response['Content-Disposition'] = 'attachment; filename=%s' % smart_str(file_name)
response['X-Sendfile'] = smart_str(path_to_file)
return response

【讨论】:

    猜你喜欢
    • 2019-04-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 2018-04-07
    • 1970-01-01
    • 2019-07-23
    • 2014-06-29
    • 1970-01-01
    相关资源
    最近更新 更多