47 lines
1.5 KiB
Python
47 lines
1.5 KiB
Python
from django import forms
|
|
from django.core.exceptions import ValidationError
|
|
from manage_coupons.models import Coupon
|
|
|
|
|
|
class CouponForm(forms.ModelForm):
|
|
class Meta:
|
|
model = Coupon
|
|
fields = [
|
|
"title",
|
|
"description",
|
|
"image",
|
|
"discount_amount",
|
|
"discount_percentage",
|
|
"valid_from",
|
|
"valid_to",
|
|
"max_redeems",
|
|
]
|
|
widgets = {
|
|
"valid_from": forms.DateTimeInput(attrs={"type": "datetime-local"}),
|
|
"valid_to": forms.DateTimeInput(attrs={"type": "datetime-local"}),
|
|
}
|
|
|
|
def clean(self):
|
|
cleaned_data = super().clean()
|
|
discount_amount = cleaned_data.get("discount_amount")
|
|
discount_percentage = cleaned_data.get("discount_percentage")
|
|
valid_from = cleaned_data.get("valid_from")
|
|
valid_to = cleaned_data.get("valid_to")
|
|
|
|
if discount_amount and discount_percentage:
|
|
raise ValidationError(
|
|
"You can only set either a discount amount or a discount percentage, not both."
|
|
)
|
|
|
|
if not discount_amount and not discount_percentage:
|
|
raise ValidationError(
|
|
"You must set either a discount amount or a discount percentage."
|
|
)
|
|
|
|
if valid_from and valid_to and valid_from >= valid_to:
|
|
raise ValidationError(
|
|
"The valid_from date must be earlier than the valid_to date."
|
|
)
|
|
|
|
return cleaned_data
|