django - How do check an instance belongs to the login user? -
below how check model belongs user that's editing it. in views.py
everything, it's bit repetitive, use lot!
# if have instance check belongs login. if some_object.user != request.user: return httpresponseforbidden()
so, i'm wondering how others address such functionality? have been thinking moving each on save method objects?
could have examples (with code) of how django developers this, there must better wayfor checking user can edit what, right?
i won't rush accepting answer, i'm interested in authoritative responses more experienced devs i'm new django.
thank you.
mixins work if using class based views... can create own doing
class requireownershipmixin(object): def get_object(self, queryset=none): obj = super(requireownershipmixin, self).get_object(queryset) if obj.user != self.request.user: return none return obj
and view this
class updatesomeobjectview(requireownershipmixin, updateview): ...
this override get_object
method return none
if not owner of object. may need checks in get
or post
methods handle when none
returned can return httpresponseforbidden
you can use class based views utilize get_object
method.
Comments
Post a Comment