Django:如何在django中写一个条件语句来检查帖子状态是否从live变为cancel?

44u64gxh  于 2022-12-24  发布在  Go
关注(0)|答案(2)|浏览(79)

我想写一个条件,当用户尝试将对象的状态更改为cancel* a,而对象中已经有participant**时,该条件将显示警告消息。条件语句似乎不起作用。

class PredictionUpdate(ProductInline, UpdateView):

    def get_context_data(self, **kwargs):
        ctx = super(PredictionUpdate, self).get_context_data(**kwargs)
        ctx['named_formsets'] = self.get_named_formsets()
        return ctx
    
    def get_current_object(self, id):
        prediction = Predictions.objects.get(id=id)
        return {
            "prediction":prediction
        }

    def get_named_formsets(self):
        return {
            'variants': PredictionDataFormSet(self.request.POST or None, self.request.FILES or None, instance=self.object, prefix='variants'),
        }

    def dispatch(self, request ,*args, **kwargs):
        obj = self.get_object()
        if obj.user != self.request.user:
            messages.warning(self.request, "You are not allowed to edit this bet!")
            return redirect("core:dashboard")
        
        if obj.status == "finished":
            messages.warning(self.request, "You cannot edit this bet again, send an update request to continue.")
            return redirect("core:dashboard")
            # raise Http404("You are not allowed to edit this Post")
        return super(PredictionUpdate, self).dispatch(request, *args, **kwargs)
    
    def form_valid(self, form):
        instance = form.instance
        if instance.participants.exists() and instance.status == 'cancelled':
            messages.warning(self.request, "You cannot cancel a bet that already have participants")
            return redirect("core:dashboard")
        else:
            form.save()
            return HttpResponseRedirect(self.get_success_url())

models.py

STATUS = (
    ("live", "Live"),
    ("in_review", "In review"),
    ("pending", "Pending"),
    ("cancelled", "Cancelled"),
    ("finished", "Finished"),
)

class Predictions(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    title = models.CharField(max_length=1000)
    participants = models.ManyToManyField(User, related_name="participants", blank=True)
    status = models.CharField(choices=STATUS, max_length=100, default="in_review")

它将帖子设置为取消,即使已经有一个参与者。我想要的是这样的,假设对象中已经有至少1个参与者,我想显示一条警告消息,说明他们无法取消帖子并将其重定向回 Jmeter 板。

csga3l58

csga3l581#

您可以覆盖form_valid()方法,然后在将其保存到数据库之前检查值

class PredictionUpdate(ProductInline, UpdateView):

    def form_valid(self, form):
        instance = form.instance
        if instance.participants.exists() and instance.status == 'cancelled':
            messages.warning(self.request, "You cannot cancel a bet that already have participants")
            return redirect("core:dashboard")
        else:
            form.save()
            return HttpResponseRedirect(self.get_success_url())
atmip9wb

atmip9wb2#

我认为不使用updateview,而只是在序列化程序中给予验证,这样做会更容易。

相关问题