Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - being able to access page only after HttpResponseRedirect

I have a class based view in which I process the form and redirect the user on successful submission like so:

views.py

def get(self,request):
    form = self.form_class()
    return render(request, template_name, { 'form' : form })
def post(self, request, *args, **kwargs):
    form = self.form_class(request.POST)
    if form.is_valid():
            ...
        return HttpResponseRedirect(reverse('success'))

return render(request, template_name, { 'form' : form })

urls.py

...
url(r'^submit/success', SubmitView.as_view(), name='success'),
...

It is possible to access url directly by typing success/submit. I don't use any authentication on the site and want the user only be able to access the submit/success page after redirection, so that they are not able to access it directly. How do I do it?

like image 396
dev4Fun Avatar asked Oct 15 '25 15:10

dev4Fun


2 Answers

If you are using sessions, you can accomplish it like so:

# in the view where form is submitted
if form.is_valid():
    request.session['form-submitted'] = True
    return HttpResponseRedirect(reverse('success'))

# in the success view
def get(self, request):
    if not request.session.get('form-submitted', False):
        # handle case where form was not submitted
    else:
        # render the template
like image 56
miki725 Avatar answered Oct 18 '25 09:10

miki725


Instead of redirecting, you could POST to the 'success' page. Then use if request.method == 'POST': But beware, this is NOT secure, as headers can be spoofed.

Better to just call the success view from within the POST method, I think.

like image 35
Rob L Avatar answered Oct 18 '25 11:10

Rob L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!