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

前端 未结 5 588
悲&欢浪女
悲&欢浪女 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:34

    You can use a session to store the hash

    import hashlib
    
    def contact(request):
        if request.method == 'POST':
            form = MyForm(request.POST)
            #join all the fields in one string
            hashstring=hashlib.sha1(fieldsstring)
            if request.session.get('sesionform')!=hashstring:
                if form.is_valid() :                                         
                    request.session['sesionform'] = hashstring
                    #do some stuff...
                    return HttpResponseRedirect('/thanks/') # Redirect after POST  
            else
               raise SubmissionWasDuplicate("duplicate")
        else:
            form = MyForm() 
    

    With this approach (not deleting the session cookie) the user can't re-store the data util the session expires, by the way, i'm assuming that exist something who identify the user who send the data

提交回复
热议问题