媒体文件404 - Django [英] 404 on media files - Django

查看:539
本文介绍了媒体文件404 - Django的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天晚上,我将我的项目上传到pythonanywhere.com,我想测试我的生产设置。在我的一个模型中,我允许用户上传 JPG(团队徽标)。上传过程很好,文件放在我的MEDIA_ROOT中。问题是,当我尝试在我的模板中访问它(显示在页面上)我得到一个404.我的第一个想法是,我的MEDIA_URL配置不正确,但我仍然不知道为什么。我想说我的媒体文件夹不在项目中 - 它在外面。
开发模式下,我看到徽标(我有if settings.DEBUG:urlpattern + = static(...)选项设置正确)。

Last night I uploaded my project to pythonanywhere.com where I wanted to test my production settings. In one of my models I allow users to upload JPG's (Logo of a team). The uploading process works good, the file lands in my MEDIA_ROOT. The issue is that when I try to access it in my template (to display it on the page) I get a 404. My first thought is that my MEDIA_URL is not configured properly but I still don't know why. I want to say that my media folder isn't in the project - it is outside. On development mode I see the Logo (I have the if settings.DEBUG: urlpattern += static(...) option set properly).

我正在使用Django 1.9.7与python 2.7
这是我的代码:

I'm using Django 1.9.7 with python 2.7 Here is my code:

我的模型:

class Team(models.Model):

name = models.CharField(verbose_name='Name of the team', max_length=24)
logo = models.ImageField(upload_to='team_logos', verbose_name='Logo', blank=True, null=True)
def get_logo(self):
    u"""Get path to logo, if there is no logo then show default."""
    if self.logo:
        return self.logo.url
    return '/static/img/default_team_logo.jpg'

我的Settings.py:

My Settings.py:

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media", "soccerV1", "static")
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "media", "static"),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "media", "soccerV1", "media")

我要调用徽标的模板:

<td><img src="{{ details.get_logo }}" alt="{{ details.name }} logo" height="64px" width="64px"></td>


推荐答案

您需要在PythonAnywhere的信息中心中设置媒体文件映射。从他们的文档

You need to set a media files mapping in PythonAnywhere's dashboard. From their documentation:


  • 转到PythonAnywhere仪表板上的 Web 选项卡

  • 转到静态文件部分

  • url 部分输入与MEDIA_URL相同的网址(在您的情况下, / media /

  • 输入MEDIA_ROOT路径到路径部分(完整路径,包括 / home / username / etc

  • Go to the Web tab on the PythonAnywhere dashboard
  • Go to the Static Files section
  • Enter the same URL as MEDIA_URL in the url section (in your case, /media/)
  • Enter the path from MEDIA_ROOT into the path section (the full path, including /home/username/etc)

然后点击重新加载,并且您的上传的文件应正确投放。

Then hit Reload and your uploaded files should be served correctly.

这篇关于媒体文件404 - Django的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆