[Answered ]-How to restrict users from going back to the previous page with the browser "back button" (redirect to a different page, instead)?


I am not sure how you get this desired behavior from Django as you have limited control over the user’s browser. However, in Javascript you can use:


which will remove history, thus preventing the back button from working.

See this stack overflow question about window location:

What's the difference between window.location= and window.location.replace()?

An idea: from your preview page, use AJAX to submit and if all is successful, window.location.replace to your posted page.


I can’t speak for how to deal with this using browser technologies but with django you could just set a flag in the session.

# posted_page view
request.session['posted_page_visited'] = True

# preview_page view
if request.session.get('posted_page_visited'):
    del request.session['posted_page_visited']
    return http.HttpResponseRedirect("form_page")


Using js (window.location.replace(url)) doesn’t fulfill this requirement because "replace url" will just replace the page with another one,Ex: if form flow goes from page1 to page2 then page3 then page4 and (window.location.replace(url)) is used in page2 (window.location.replace(page4);) then page3 will never be visited!! moreover user will still be able to go back in the same forward path meaning from page4 to page2…etc

the good thing, you can solve it by using Django session as shown below assuming users will be able to go back and forth as long as form not yet saved, and once its saved they can’t go back anymore:

in page1/view function where first part of form is issued create session varaible:

in view1.py

def view1(request)
     request.session['forward'] = True
        return redirect(....)

in view2.py:

def view2(request):
if not request.session['forward']:
   return redirect(..Select whatever page you want to redirect users to it..) 

the same in rest of pages views..

in the last page/view where after saving the form, reset the variable:

request.session['forward'] = False
return redirect(..Select whatever page you want to redirect users to it..)

hopes its clear enough


django’s form wizard should do what you want:

How it works

Here’s the basic workflow for how a user would use a wizard:

  1. The user visits the first page of the wizard, fills in the form and submits it.
  2. The server validates the data. If it’s invalid, the form is displayed again, with error messages. If it’s valid, the server saves
    the current state of the wizard in the backend and redirects to the
    next step.
  3. Step 1 and 2 repeat, for every subsequent form in the wizard.
  4. Once the user has submitted all the forms and all the data has been validated, the wizard processes the data – saving it to the
    database, sending an email, or whatever the application needs to do.

Leave a comment