【发布时间】:2011-02-16 13:36:14
【问题描述】:
为了避免垃圾邮件,我想添加一个等待时间来重新提交表单(即用户应该等待几秒钟来提交表单,除了第一次提交表单之外)。
为此,我在表单中添加了一个timestamp(以及一个包含时间戳的security_hash 字段以及确保时间戳不会被篡改的settings.SECRET_KEY)。这看起来像:
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...
这很好用。但是还有一个问题:用户第一次提交表单时会检查时间戳,我需要避免这种情况。
有解决办法吗?
谢谢! :-)
【问题讨论】:
-
你为什么不在用户的会话中记录这个?
-
我认为 session 也是要走的路。
标签: python django forms django-forms timestamp