如何防止用户在 24 小时后更新帖子 django

我想阻止用户在发布日期后 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 小时之前更新帖子 谢谢


缥缈止盈
浏览 82回答 1
1回答

一只甜甜圈

您可以过滤查询集,使其仅包含Post最近 24 小时内撰写的帖子:from datetime import timedeltafrom django.utils.timezone import nowclass 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 响应。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python