Django Media Files (Images) Security

Viewed 574

I am working on image handling in Django. I am using normal image model storing method.

So, my model is something like,

class PictureModel(models.Model):
    def user_directory_path(instance, filename):
        return 'images/{0}/{1}'.format(instance.user.username, filename)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    image = models.ImageField(upload_to=user_directory_path)

The view.py is somewhat like,

@login_required(login_url='/accounts/login/')
def myMethod(request):
    user = request.user
    myImage = PictureModel.objects.get(user=request.user)
    return render(request, 'main/myPage.html', {'myImage': myImage})

I have a media root setup as,

MEDIA_ROOT =  os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

The url.py setup is as follows,

url(r'^static/(?P<path>.*)$', django.views.static.serve, {'document_root': settings.STATIC_ROOT, 'show_indexes': settings.DEBUG})

Now in normal flow, the image uploading and fetching are working as expected. But the issue is regarding the user validation/authentication while fetching the media file.

Suppose, I am getting an image by the URL,

media/images/user_1/mypic.jpg

But the whole media folder gets exposed without any validations and I can access,

media/images/user_2/mypic.jpg

also through the browser. I have searched on this over the net and found there are some random third party libraries are available but they are not so standard/popular. Can anyone suggest the best practices and libraries to handle the situation.

1 Answers

Add this in your template it solves the problem

<img style="height:200px; width:200px; border-radius:50%; margin:auto" src="{{ appname.function_name.image.url }}" alt="Photo">
Related