Haris Bašić
Haris Bašić

Reputation: 1383

Serving files with user restrictions with Django

I need help with this one. In my application users are connected with projects. Let's say I want to enable download of files just for user if has created_by field in file model equal to request.user.

How is that possible. Is there any generic view or something?

Upvotes: 1

Views: 63

Answers (1)

bogeylicious
bogeylicious

Reputation: 5170

Add a method to the model that can be used in the view. Something like this:

class File:
    created_by = models.ForeignKey(User)
    # NOTE other fields go here...

    def is_downloadable_by_user(self, request):
        return self.created_by == request.user

Then in your view you can do something like this:

# NOTE fix import based on project configuration
import File

@login_required
def my_view(request):
    # NOTE get file instance however you want
    file = File(id=1)
    if file.is_downloadable_by_user():
        # DO SOMETHING

With some tweaks, I imagine this approach should work for you. The @login_required is a default Django decorator.

Upvotes: 1

Related Questions