After a user updates a record and submits a POST request, what's the best way to redirect them to the previous page? I know there's a potential issue with using the HTTP_REFERER method however the user will be using not be using a browser with custom settings.
Example from the views.py - This does not work (it only refreshes the page)
class example(LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = example
template_name = 'storiesapp/example.html'
fields = ['title']
def form_valid(self, form):
form.instance.fk_user = self.request.user
form.save()
return HttpResponseRedirect(self.request.META.get('HTTP_REFERER'))
def test_func(self):
post = self.get_object()
if self.request.user == post.fk_user:
return True
return False
If I remove 'self', I receive a PK expected error, if I add a PK, i'm directed immediately to my profile
.
.
I've tried the below, but recieve an error
This allows me to click through to edit the data but upon saving to update, it gives me an error that it expects a PK. If I change the def post to (self, request, pk) - when clicking on the record to update it takes me immediately to my profile instead of the template that allows me to update in the first place.
class pictures_update (LoginRequiredMixin, UserPassesTestMixin, UpdateView):
model = pictures
fields = ['name', 'date']
template_name = 'storiesapp/pictures.html'
def form_valid(self, form):
form.instance.fk_user = self.request.user
form.save()
def get(self, request):
next_url = request.POST.get('next') if 'next' in request.POST else 'profile'
return redirect(next_url)
def test_func(self):
post = self.get_object()
if self.request.user == post.fk_user:
return True
return False
.
.
If I combine the first two together, it only allows 2 arguments to be passed, whichever is listed third is ignored and causes an error. In this example, it tells me 'form' was expected.
def form_valid(self, request, form):
next_url = request.POST.get('next') if 'next' in request.POST else 'profile'
form.instance.fk_user = self.request.user
form.save()
return redirect(next_url)