i want to write a condition that would show a warning message when a user try to change the status of a an object to cancel that already have a participant in the object. The conditional statement seems not to be working.
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")
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 redirect them back to the dashboard.
CodePudding user response:
You can override the form_valid()
method and then check the values before saving it to the database
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())
CodePudding user response:
I think instead of using updateview just give validation in serializer. its would more easy do.