Is there recommended way of restricting file view to declared urls? More precisely, the image should be displayed if accessed through template {{ image. url }} , but it shouldn’t be accessible if accessed by direct url /media/images/image.jpg (i. e. by opening image in new tab).
I thought of adding new path to urlpatterns media/images/<str:file> for catching all attempts to access files, but from what I see calling a file from within template simply makes new request and it’s not possible to differentiate between template call and direct call.
Hello there!
Are you trying to restrict access based on some condition?
Like, if the user is logged in, or based on some other permission that the user has?
You’re not missing anything. From the perspective of the server, a request is a request. There is nothing to distinguish one type of request from another.
If you want to limit the requests by user or permission, that can be done using nginx, but it does nothing to enforce that the request come from an img tag instead of a separate browser tab.
No, just based on whether it’s accessed from the template or not. I can do a little bit of workaround, setting additional parameter on the model containing file, but perhaps there’s another way.
The FileField is containing images uploaded by users and I’d like to avoid having something nasty uploaded and shared on the page. If user is accessing the images through the template, the view is dividing it into moderated (will display the page) and non-moderated (will display info that the work is waiting for moderation). So from the template view, it’s restricted.
I’m thinking about adding additional param on the model containing file and catch if it’s not ‘moderated’, it won’t be accessible (only for mods). I’d still prefer the image to not be accessible by direct link, so if anyone has idea how to wrap it, I am all ears.
You can’t enforce this. The HTTP protocol simply doesn’t provide any mechanism for this to be practical. Don’t waste your time trying to find a solution.