我正在学习django,我有一个测试页面,允许用户“联系我们” - 它正在工作 - 电子邮件正在我的本地开发服务器上传送。
我已经尝试了两天(我已阅读过SO帖子,django docs,google和一些教程),并且无法锻炼如何执行以下操作:
如何设置时间延迟,以便用户在向“联系我们”发送另一封电子邮件之前必须等待3分钟(或左右)?这将是一项阻止同一个用户用电子邮件轰炸'contact_us' - 用户必须在电子邮件之间等待3分钟(或左右)。
我想过用JQuery完成这个,但是用户不能在客户端绕过这个设置吗?
这是我的models.py文件:
class Contact(models.Model):
name = models.CharField(null=True, blank=True, max_length=100)
email = models.EmailField(null=False, blank=False, max_length=250)
reason = models.PositiveIntegerField(choices=REASON_TYPES, default=SELECT_REASON_TYPE, validators=[MinValueValidator(1)])
message = models.TextField(null=False, blank=False, max_length=2000)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
def __unicode__(self, ):
return "Message from: " + str(self.email)
这是我的forms.py文件:
class ContactForm(forms.ModelForm):
class Meta:
model = Contact
fields = (
'name',
'email',
'reason',
'message',
)
labels = {
'name': _('Name'),
'email': _('E-mail'),
'reason': _('Reason'),
'message': _('Message'),
}
help_texts = {
'message': _('2,000 character limit'),
}
error_messages = {
'reason': {'validate_min': _('This field is required.')}, # validate_min used on achievement_type in lieu of required field.
}
这是我的views.py文件:
def contact_us(request):
form = ContactForm(request.POST or None)
if form.is_valid():
save_form = form.save(commit=False)
send = send_mail(str(save_form.reason), str(save_form.message), str(save_form.email), ['XXX@gmail.com'], fail_silently=True)
save_form.save()
messages.success(request, _('message successfully delivered.'))
return render_to_response('contact_us/contact_us.html', locals(), context_instance=RequestContext(request))
这是我的urls.py文件:
urlpatterns = patterns(
'',
....
url(r'^contact_us/', 'contact.views.contact_us', name='contact_us'),
....
)
答案 0 :(得分:2)
您可以使用django会话变量来存储用户发送最后一封电子邮件的确切时间。如果当前时间少于3分钟,只需将会话变量更新为当前时间并发送电子邮件,否则,不允许用户发送电子邮件。
def contact_us(request):
last_send_time = request.session.get('last_email_time',None)
if last_send_time:
current_time = datetime.datetime.now()
diff = current_time - last_send_time
minutes_diff = divmod(diff.days * 86400 + diff.seconds, 60)
if minudes_diff[0] > 3: #minutes_diff[0] has difference between current_time and last_send_time
//Handle this case, user cant send email again
return render_to_response('contact_us/contact_us.html', locals(), context_instance=RequestContext(request))
else:
request.session['last_email_time'] = current_time
form = ContactForm(request.POST or None)
if form.is_valid():
save_form = form.save(commit=False)
send = send_mail(str(save_form.reason), str(save_form.message), str(save_form.email), ['XXX@gmail.com'], fail_silently=True)
save_form.save()
messages.success(request, _('message successfully delivered.'))
return render_to_response('contact_us/contact_us.html', locals(), context_instance=RequestContext(request))