Dawid Dave Kosiński Dawid Dave Kosiński - 2 months ago 14x
Python Question

404 on media files - Django

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

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

My model:

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'

My Settings.py:

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

And my template where I call for the logo:

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


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

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