Reputation: 2197
Here is the problem: I have an Update view with overridden get_object method :
class MyUpdateView(SuccessMessageMixin, LoginRequiredMixin, UpdateView):
some code here:
def get_object(self, queryset=None):
obj = UpdateView.get_object(self, queryset=None)
if not obj.author == self.request.user:
redirect(reverse_lazy("app:url")) # or reverse instead , no difference
return obj
p.s. object.author tied via foreign key to a user model(self.request.user in our case)
In this view I want to allow to edit entry only to the users who created this exact entry. I know how to do it via get_queryset or via UserPassesTestMixin but both methods raise errors . Instead i need redirect user who is not the author back to the page where he came from or to a certain URL (parametrical) .
In this case(code is bellow) it works fine, 404 appears , so that logic works. I tried it via web site: author able to edit entry, non - author would conjure 404 .
# in this case it forks fine, 404 appears :
def get_object(self, queryset=None):
obj = UpdateView.get_object(self, queryset=None)
if not obj.author == self.request.user:
raise Http404
return obj
But in first example redirect doesn't work for some reason.
I have tried - get_queryset
or UserPassesTestMixin
, but it not what I need
autor = request.user - allow to edit entry
author != request.user - go to the previous page ot to a certain URL + message
If someone has any idea how to use redirect in this case -please answer. have anice day
---solution ---
def get(self, request, **kwargs):
if self.get_object().author == self.request.user:
return UpdateView.get(self, request, **kwargs)
else:
messages.add_message(request, messages.WARNING, "You can only change your own entries")
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Upvotes: 1
Views: 368
Reputation: 1373
You need to go back and then aware the user with a message using the django message framework The proper way to do this is
from django.http import HttpResponseRedirect
def someview(request):
...
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Upvotes: 3