I have an update view that is working properly. The only issue is currently anyone can edit any post. To solve this issue I implemented the LoginRequiredMixin
and UserPassesTestMixin
. I believe I have implemented it correctly but any one is still able to edit any post.
view:
class PostUpdateView(UpdateView, LoginRequiredMixin, UserPassesTestMixin):
model = Post
form_class = PostFormUpdate
template_name = 'update_post.html'
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user == post.author:
return True
return False
CodePudding user response:
The order of superclasses extended matters, so UserPassesTestMixin
should come before UpdateView
:
class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
I'm surprised that this is not mentioned in the documentation for UserPassesTestMixin
, but you can get the hint from LoginRequired
:
This mixin should be at the leftmost position in the inheritance list.
As a side note you can simply do
return self.request.user == post.author
As it is already a boolean value. No need for an if
clause.