2

strong textI am trying to prevent a page being cached as I dont want the user to be able to resubmit a form which has already been saved to the db.

I tried the following in views.py

class ServiceCreate(LoginRequiredMixin, CreateView):
    model = Service
    form_class = ServiceCreateForm

    @method_decorator(never_cache)
    def dispatch(self, request, *args, **kwargs):
        return super(ServiceCreate, self).dispatch(request, *args, **kwargs)

However, this has no effect as the entire page is shown instantly when the user hits the back button. How can I prevent caching please?

Update I'm new to Django so thought that the decorator would instruct the browser not to cache - I did not appreciate that there was server caching as well.

RunLoop
  • 20,288
  • 21
  • 96
  • 151

1 Answers1

5

What you're seeing has nothing to do with server caching- it is all browser side.

Ultimately you can't 100% guarantee that a form won't be submitted multiple times (users will find a way...), so you'll have to handle that gracefully on the server. However you can greatly reduce the likelihood of it:

  • Return an HttpResponseRedirect (or use the redirect shortcut) to redirect the browser after a successful form submission. This will prevent a browser refresh from resubmitting the form.

  • Use javascript to disable the form submit button after the form as been submitted. I recently had some weird errors and data inconsistencies that turned out to be caused by someone double clicking a form's submit button. Disabling the button after the first click resolved the issue (along with doing more validation server-side to recognize a duplicate submission).

  • Make sure that you use POST (rather than GET) to submit the form. Browsers are less likely to resubmit the form casually and I believe that Django's CSRF protection should also help prevent errant submissions.

Community
  • 1
  • 1
dgel
  • 16,352
  • 8
  • 58
  • 75
  • Thanks for your thorough answer. I think your second suggestion of disabling the submit button will be the best. – RunLoop Jul 03 '15 at 05:59