Venor
Venor

Reputation: 347

Django shared db with restricted views per user

I have a db that is to be shared. Where if a object has a certain value I need specific users to be able to see and edit it. No other users can see or edit these objects.

I am trying to understand what way one should do this. I don't know django very well. I am currently looking at conditionals for views. Not sure if that is even possible given i don't know if conditionals on views can filter objects.

If anyone could point me in the right direction I would greatly appreciate it.

Upvotes: 0

Views: 33

Answers (1)

Tyberius
Tyberius

Reputation: 34

You should you use your views to limit what a user can see and can do. For example, to limit the list that users can view to only ones created by them then tell the query in the view to only get ones where the created user equals the requesting user. With the model views you can modify the functions to get the data you want. IF you change the get queryset function to only get where the user is the requesting user you get what you want.

   def get_queryset(self):
        return self.model.objects.filter(user=self.request.user)

The view is the logic for where users get their data so you set the conditions there.

For update you put validation before you request the form in the update view. This tells the code that if the object the user requested was note created by that user then then give a permission denied.

def dispatch(self, request, *args, **kwargs):
    obj = self.get_object()
    if obj.user != self.request.user:
        raise PermissionDenied  # HTTP 403
    else:
        return super(UpdateView, self).dispatch(request, *args, **kwargs)

Place these functions inside of your view classes and make sure to have the user field on your models.

Upvotes: 1

Related Questions