How to access user uploaded files

Hi,

I have an image upload field within my model and what to show the image within other screens. Whats the correct way to display these images within a production environment?

I’ve set a media root path within the settings.py and the path in the model which is working.

Ideally, i’d like to access the file in the same way as using {% static '' %}assets/img/uploadedfile.jpg" but i think this only works when using collectstatic?

Do not confuse “static” files with “media” files.

Static files are created and managed as part of the project itself.

Media files are user-uploaded files.

They have separate settings and configuration options. They are managed and controlled differently.

See all the docs on Media Files.

I’ve looked over these, but I find the documentation hard to follow. I’ve set the media root and url. and then I’m lost at what to do next in order for me to pass the image path into my template.

I am making progress with Django/Python but I think the documentation for beginners isn’t the easiest to follow. Hence why I ask a lot of questions on here.

I’ll keep trying different things to see if I can get any further.

One of the key differences between static files and media files is that media files are represented by a FileField in a model. Take a look at the FileField docs to find what attribute of that field is available to you to get the url for a file.

Thanks, Ken. So do I need to create a path in the url.py to get to the {{ object.mug_shot.url }}. I can’t see this in the documentation.

See Serving files uploaded by a user during development

Thanks again, Ken. I must have been missing the links to the other documentation you provided.

This is working now but will look at serving the files from some kind of storage account so that I can run this in production.

Cheers

Tom