在Django中,可以通过限制用户实例的表单填写次数来实现每天一次的限制。下面是一个实现该功能的示例:
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
last_submission = models.DateTimeField(null=True, blank=True)
from django import forms
from django.utils import timezone
class MyForm(forms.Form):
# 表单字段定义
def clean(self):
cleaned_data = super().clean()
user = self.request.user # 获取当前用户
last_submission = user.userprofile.last_submission
if last_submission and last_submission.date() == timezone.now().date():
raise forms.ValidationError("每天只能填写一次表单")
return cleaned_data
from django.shortcuts import render
from .forms import MyForm
def my_view(request):
if request.method == 'POST':
form = MyForm(request.POST)
if form.is_valid():
# 处理表单数据
form.save()
# 保存用户最后填写时间
user = request.user
user.userprofile.last_submission = timezone.now()
user.userprofile.save()
return render(request, 'success.html')
else:
form = MyForm()
return render(request, 'form.html', {'form': form})
这样,每个用户每天只能填写一次表单。如果用户尝试再次填写表单,将会收到一个错误提示。
腾讯云相关产品推荐:云服务器(ECS),产品介绍链接地址:https://cloud.tencent.com/product/cvm
领取专属 10元无门槛券
手把手带您无忧上云