2

I don't know this is a typical thing to do in web application, but what we achieve is that, let's say we have a Person model, inside this model, we have a FileField stores user's photo:

class Person(models.Model):
    photo = models.FileField(upload_to='Person_photo')

What I want to achieve is that only the owner can see his or her photo. People who log on a different account or even not log in should not be able to see the photo. Let's assume we have a way to check whether a photo belongs to a certain user or not:

def permission(photo_filename, pid):
    # return True if photo_filename exists and belongs to the person pid

We can figure this part out, for example, use permission system provided in Django. Of course from the views.py we can control whatever image we want to show on the page, but for example, we want to block people make attempts to figure out the URLs and get the photo, for example, typing

http://some.domain/media/Person_photo/Amy.jpg

in URL bar in the browser should only work if she is Amy. What is a good way to do it? Is there a library for this purpose?

TimeString
  • 1,778
  • 14
  • 25
  • You *might* be able to still use regex in your url patterns for this: url(r'/(.)/(.)/*.jpg (obviously not that, but you get the idea) and then use the parameters to return a response with the correct file. This answer may also be helpful: http://stackoverflow.com/a/2690263/4974980 – Jens Astrup Oct 12 '16 at 00:36
  • 1
    Due to the typical Django deployment, where static and media files are served by the webserver and not Django it will not be trivial. A poor mans solution would be to safe the pic under a name made from its own SHA (or similar) hash. – Klaus D. Oct 12 '16 at 00:37

1 Answers1

1

You can define view for this

view.py

from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.contrib.auth.decorators import login_required

from appname.models import Person

@login_required
def show_photo(request):
    person = get_object_or_404(Person, user=request.user)
    response = HttpResponse(person.photo.read(), content_type="image/jpg")
    response['Content-Disposition'] = 'filename=photo.jpg'
    return response

urls.py

urlpatterns += [
    url(r'^photo/$', show_photo),
]

Users will only see their photo.

Sergey Gornostaev
  • 7,596
  • 3
  • 27
  • 39