Does a library to prevent duplicate form submissions exist for django?

前端 未结 5 627
悲&欢浪女
悲&欢浪女 2020-12-06 04:55

I am trying to find a way to prevent users from double-submitting my forms. I have javascript that disables the submit button, but there is still an occasional user who fin

5条回答
  •  甜味超标
    2020-12-06 05:37

    Kristian Damian's answer is really a great suggestion. I just thought of a slight variation on that theme, but it might have more overhead.

    You could try implementing something that is used in django-piston for BaseHandler objects, which is a method called exists() that checks to see if what you are submitting is already in the database.

    From handler.py (BaseHandler):

    def exists(self, **kwargs):
        if not self.has_model():
            raise NotImplementedError
    
        try:
            self.model.objects.get(**kwargs)
            return True
        except self.model.DoesNotExist:
            return False
    

    So let's say make that a function called request_exists(), instead of a method:

    if form.is_valid()
        if request_exists(request):
            # gracefully reject dupe submission
        else:
            # do stuff to save the request
            ...
            # and ALWAYS redirect after a POST!!
            return HttpResponseRedirect('/thanks/') 
    

提交回复
热议问题