【问题标题】:django- how to serve an image in all templates of django app?django-如何在 django 应用程序的所有模板中提供图像?
【发布时间】:2017-07-03 07:19:00
【问题描述】:

我想在我的 django 项目的所有页面中显示用户的头像。 我在 base.html 和我写的 href 中使用 <img> 标记:{{ request.user.profile.get_avatar }}。 但它不能正常工作。 在项目的第一页它可以工作,但在另一个页面不起作用。

问题在于地址。 例如,在图像显示的网址为 www.mysite.com/index 的索引页面中。但在 www.mysite.com/v1/v2/v3 中没有显示图片。

这是profile类的get_avatar方法:

def get_avatar(self):
    if self.avatar:
        return os.path.join(settings.MEDIA_URL + str(self.avatar))
    else:
        return os.path.join(settings.MEDIA_URL + str('avatars/student.jpg'))

view of not working picture

def profile_me(request):
    the_profile = get_object_or_404(Profile, user=request.user)
    klasses = KlassStudents.objects.filter(student=request.user.profile)
    return render(request, 'ejazeostad/profile/profile.html', {'profile': the_profile, 'klasses': klasses})

【问题讨论】:

  • 请显示一个不起作用的视图。
  • 您是否将 'django.core.context_processors.request', 添加到 settings.py 中的 TEMPLATES = [] 变量中?
  • @Hybrid this "django.template.context_processors.request" 在 TEMPLATES 变量中...现在我将 'django.core.context_processors.request' 添加到 TEMPLATES 变量并生成此错误:没有模块命名为 'django.core.context_processors'
  • 有道理,它是请求上下文处理器的较新版本......正如@Alasdair所说,你能提供一个不起作用的视图吗?

标签: django django-templates


【解决方案1】:

MEDIA_URL 设置应为绝对 URL,例如

MEDIA_URL = '/files/'

目前,您有一个相对 URL 'files/'。这意味着 URL 会根据您所在的页面而变化。当您访问www.mysite.com/index时,相对URL会扩展为www.mysite.com/files/avatars/avatar.jpg,这是可行的,但是当您访问www.mysite.com/v1/v2/v3时,相对URL会扩展为www.mysite.com/v1/v2/files/avatars/avatar.jpg,这是不正确的。

【讨论】:

  • 没错!由于MEDIA_URL开头没有使用/,所以每一页图片的地址(url)都在变化。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
  • 2015-02-09
  • 1970-01-01
  • 1970-01-01
  • 2021-12-31
  • 2012-11-02
相关资源
最近更新 更多