1
You don’t show how you’re associating the order with the event in the first place. If you haven’t done that, then your problem is wider than just validating the tickets available.
I would recommend passing that Event from the view into the form instantiation. You can then use it both to associate the order with that event, and to validate the tickets.
class OrderForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.event = kwargs.pop('event', None)
super(OrderForm, self).__init__(*args, **kwargs)
def clean_num_tickets(self):
tickets = self.cleaned_data["num_tickets"]
if tickets > self.event.tickets_remaining:
raise ValidationError('Too many tickets')
return tickets
def save(self, commit=False):
order = super(OrderForm, self).save(commit=False)
order.event = self.event
if commit:
order.save()
return commit
Now pass the event into the form when instantiating it:
form = OrderForm(request.POST, event=event)
Source:stackexchange.com