Django:提高ValidationError不起作用

时间:2018-08-08 08:00:27

标签: django forms

任何可以解释我的人,为什么我的表单中的ValidationError不起作用?我可以在终端中看到“测试”,但是没有显示ValidationError。我很乐意分享完整的代码,但也许错误已经在下面的代码段中了?

def clean_ticket(self):
        ticket = self.cleaned_data['ticket']
        if not self.event == ticket.event:
            print("Test")
            raise forms.ValidationError(
                _("The ticket you chose doesn't belong to your event."),
                code='ticket_belongs_to_event_validation',
            )
        return ticket

全长代码:

class ReserveForm(forms.ModelForm):
    """
    * Pass inital tickets into form.
    * Check if quantity is lower than defined max qty per ticket.
    * Check if quantity is available.
    * Clean function for quantity field.
    """
    class Meta:
        model = ReservedItem
        fields = ['ticket', 'quantity']

    def __init__(self, organizer, event, *args, **kwargs):
        self.organizer = organizer
        self.event = event
        self.ticket = kwargs['initial']['ticket']
        super().__init__(*args, **kwargs)
        self.fields['ticket'].widget = forms.HiddenInput()
        self.fields['quantity'].widget.attrs['placeholder'] = '0'
        self.fields['quantity'].widget.attrs['class'] = 'form-control'  # TODO Marc

    def check_if_qty_lower_than_max_qty_per_ticket(self, new_added_quantity, max_qty_per_ticket):
        if new_added_quantity and new_added_quantity > max_qty_per_ticket:
            raise forms.ValidationError(
                _("You can only buy %(max_quantity)s tickets per ticket type."),
                code='max_qty_per_ticket',
                params={'max_quantity': max_qty_per_ticket},
            )

    def check_if_qty_is_available(self, new_added_quantity):
        ticket_pk = self.ticket.pk
        ticket_name = self.ticket.name
        max_quantity = self.ticket.quantity

        # Check OrderItem
        order_items_qty = OrderItem.objects.filter(
            ticket__pk=ticket_pk
        ).aggregate(Sum('quantity'))

        # Check ReservedItem within the last x minutes
        time_threshold = timezone.now() - timedelta(minutes=settings.MINUTES_TICKET_RESERVATION)
        reserved_items_qty = ReservedItem.objects.filter(
            ticket__pk=ticket_pk,
            created__gt=time_threshold,
        ).aggregate(Sum('quantity'))

        # Calculate reserved quantity and new quantity
        order_items_qty = order_items_qty['quantity__sum']
        reserved_items_qty = reserved_items_qty['quantity__sum']
        order_items_qty = 0 if not order_items_qty else order_items_qty
        reserved_items_qty = 0 if not reserved_items_qty else reserved_items_qty

        qty_reserved = order_items_qty + reserved_items_qty
        new_quantity = qty_reserved + new_added_quantity

        # Validation
        if new_quantity > max_quantity:
            tickets_left_total = max_quantity - qty_reserved
            raise forms.ValidationError(
                _("%(ticket_name)s: There are not enough tickets left. Maximum you can choose is %(value)s."),
                code='qty_available',
                params={'ticket_name': ticket_name, 'value': tickets_left_total},
            )

    def clean_ticket(self):
        ticket = self.cleaned_data['ticket']
        if not self.event == ticket.event:
            print("Test")
            raise forms.ValidationError(
                _("The ticket you chose doesn't belong to your event."),
                code='ticket_belongs_to_event_validation',
            )
        return ticket


    def clean_quantity(self):
        new_added_quantity = self.cleaned_data['quantity']
        if new_added_quantity:
            self.check_if_qty_lower_than_max_qty_per_ticket(
                new_added_quantity=new_added_quantity,
                max_qty_per_ticket=self.organizer.max_qty_per_ticket,
            )
            self.check_if_qty_is_available(
                new_added_quantity=new_added_quantity,
            )

        # Always return a value to use as the new cleaned data, even if
        # this method didn't change it.
        return new_added_quantity

0 个答案:

没有答案