How should I enforce permission checking when file is reached/downloaded in Django?
<p>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 <code>FileField</code> stores user's photo:</p>

<pre><code>class Person(models.Model):
    photo = models.FileField(upload_to='Person_photo')
</code></pre>

<p>What I want to achieve is that <em>only</em> 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:</p>

<pre><code>def permission(photo_filename, pid):
    # return True if photo_filename exists and belongs to the person pid
</code></pre>

<p>We can figure this part out, for example, use permission system provided in Django. Of course from the <code>views.py</code> 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</p>

<pre><code>http://some.domain/media/Person_photo/Amy.jpg
</code></pre>

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

<p>You can define view for this</p>

<p><strong>view.py</strong></p>

<pre><code>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
</code></pre>

<p><strong>urls.py</strong></p>

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

<p>Users will only see their photo.</p>

python django