How to build a Django form which requires a delay to be re-submitted ?
Posted
by pierre-guillaume-degans
on Stack Overflow
See other posts from Stack Overflow
or by pierre-guillaume-degans
Published on 2010-05-06T20:08:18Z
Indexed on
2010/05/06
20:18 UTC
Read the original article
Hit count: 286
Hey,
In order to avoid spamming, I would like to add a waiting time to re-submit a form (i.e. the user should wait a few seconds to submit the form, except the first time that this form is submitted).
To do that, I added a timestamp
to my form (and a security_hash
field containing the timestamp plus the settings.SECRET_KEY
which ensures that the timestamp is not fiddled with). This look like:
class MyForm(forms.Form):
timestamp = forms.IntegerField(widget=forms.HiddenInput)
security_hash = forms.CharField(min_length=40, max_length=40, widget=forms.HiddenInput)
# + some other fields..
# + methods to build the hash and to clean the timestamp...
# (it is based on django.contrib.comments.forms.CommentSecurityForm)
def clean_timestamp(self):
"""Make sure the delay is over (5 seconds)."""
ts = self.cleaned_data["timestamp"]
if not time.time() - ts > 5:
raise forms.ValidationError("Timestamp check failed")
return ts
# etc...
This works fine. However there is still an issue: the timestamp is checked the first time the form is submitted by the user, and I need to avoid this.
Any idea to fix it ?
Thank you ! :-)
© Stack Overflow or respective owner