Forums

Django: user uploaded images only shown when logged in pythonanywhere

I have this problem where my images are only shown when logged in pythonanywhere. Static images work fine (css, js, png ..). But user uploaded images lack the permission to be shown to anonymous website users.

Here are my specs:

Django 1.8 with virtualenv


settings:

DEBUG = True;

ALLOWED_HOSTS = [],

MEDIA_ROOT ="/home/username/projectname/media",

MEDIA_URL = "/media/"


model:

img = models.ImageField(upload_to="")


template:

in a img tag I have:

src="https://www.pythonanywhere.com/user/username/files/home/username/projectname{{ context_variable_name.img.url }}"


webtab:

/media/

/home/username/projectname/media


Everyting I tried didn't work. I could use aws s3. But I would prefer pythonsanywhere storage system.

Thank you very much, for anykind of advice.

The problem is in the src tag you're using for your images. You shouldn't be trying to access them from the PythonAnywhere site, you should use an address on your own site.

To make the files in the directory /home/username/projectname/media available on your own site, go to the "Web" tab and add an entry to the "Static files" table. The "URL" should be something like /media and the directory should be /home/username/projectname/media. You may find you have an entry like that already -- I think we generate one for you by default.

Once you've done that, the URL you should use in the img tags should be /media/{{ context_variable_name.img.url }}.

Here's why: URLs like this:

https://www.pythonanywhere.com/user/username/files/...

are only available when you're logged in to PythonAnywhere, as you've noticed. This is because if they were available to people who weren't logged in, anyone on the Internet would be able to access all of your files, including sensitive data like your code, your database passwords and the secret key in the settings.py file.

The static files table on the "Web" tab is there to allow you to specify particular directories that you don't mind sharing with the whole world.