I'm adding some user profile behavior to a Django app, and as usual I would like to restrict users from only being able to interact with their own data. This SO Q&A is related to the process itself:
Django--- Allowing Users to only edit their profile
Is it enough to add the authenticated user id to the create, update, and delete queries? To reduce code duplication, I was thinking that I could write a mixin that would override get_object
or get_queryset
and intercept the query by adding the self.request.user.pk
to filter the results?
Are there other efficient methods for doing this, or mixins from Django itself?
edit This is what i was thinking:
class OwnersDataOnlyViewMixin(object):
def get_object(self, queryset=None):
if self.model == get_user_model():
# user model, so pk of model should match self.request.user.pk
return super().get_object(self.model.objects.filter(pk=self.request.user.pk))
else:
# different model
try:
# check for the 'user' field and filter on it if found
user_field = self.model._meta.get_field('user')
return super().get_object(self.model.objects.filter(user=self.request.user))
except:
# Mixin was used with model data not associated with a user
raise self.model.DoesNotExist
There are probably more flexible ways of doing this, and I'm open to suggestions to improve that.