我想阻止用户在发布日期后 24 小时后更新帖子class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title= models.CharField(max_length=50) post = models.TextField(max_length=400) date = models.DateTimeField(auto_now_add=True) edit = models.DateTimeField(auto_now=True)class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__'class PostUpdateView(LoginRequiredMixin,SuccessMessageMixin,UpdateView): model = Post form_class = PostForm success_message = "updated successfully" template_name = 'store/create.html' success_url = reverse_lazy('lists') def form_valid(self,form): return super().form_valid(form)我想让用户只能在发布日期的 24 小时之前更新帖子 谢谢
1 回答
一只甜甜圈
TA贡献1836条经验 获得超5个赞
您可以过滤查询集,使其仅包含Post最近 24 小时内撰写的帖子:
from datetime import timedelta
from django.utils.timezone import now
class PostUpdateView(LoginRequiredMixin,SuccessMessageMixin,UpdateView):
model = Post
form_class = PostForm
success_message = "updated successfully"
template_name = 'store/create.html'
success_url = reverse_lazy('lists')
def get_queryset(self, *args, **kwargs):
return super().get_queryset(*args, **kwargs).filter(
date__gte=now() - timedelta(days=1)
)
def form_valid(self,form):
return super().form_valid(form)
如果更新周期已“过期”,这将返回 HTTP 404 响应。
添加回答
举报
0/150
提交
取消