i want to write a condition that would show a warning message when a user try to change the status of a post to cancel , if the post already have a participant in it. The conditional statement seems not to be working.
It sets the post to cancel even if there is already a participant. what i want is this, provided there is already at least 1 participant in the object, i want to show a warning message that they cannot cancel the post and then i redirect them back to the dashboard.
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())
complete code
class PredictionUpdate(LoginRequiredMixin, 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_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 get_success_url(self):
return reverse("core:dashboard")
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())