You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

forms.py 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import datetime
  2. from django import forms
  3. from django.db.models.loading import get_model
  4. from django.utils.translation import ugettext_lazy as _
  5. ConditionalOffer = get_model('offer', 'ConditionalOffer')
  6. Condition = get_model('offer', 'Condition')
  7. Benefit = get_model('offer', 'Benefit')
  8. class MetaDataForm(forms.ModelForm):
  9. class Meta:
  10. model = ConditionalOffer
  11. fields = ('name', 'description')
  12. class RestrictionsForm(forms.ModelForm):
  13. format = '%Y-%m-%d %H:%M'
  14. start_datetime = forms.DateTimeField(
  15. widget=forms.DateTimeInput(format=format),
  16. label=_("Start date"), required=False)
  17. end_datetime = forms.DateTimeField(widget=forms.DateTimeInput(format=format),
  18. label=_("End date"), required=False)
  19. def __init__(self, *args, **kwargs):
  20. super(RestrictionsForm, self).__init__(*args, **kwargs)
  21. today = datetime.date.today()
  22. self.fields['start_datetime'].initial = today.strftime(self.format)
  23. class Meta:
  24. model = ConditionalOffer
  25. fields = ('start_datetime', 'end_datetime',
  26. 'max_basket_applications', 'max_user_applications',
  27. 'max_global_applications', 'max_discount')
  28. def clean(self):
  29. cleaned_data = super(RestrictionsForm, self).clean()
  30. start = cleaned_data['start_datetime']
  31. end = cleaned_data['end_datetime']
  32. if start and end and end < start:
  33. raise forms.ValidationError(_(
  34. "The end date must be after the start date"))
  35. return cleaned_data
  36. class ConditionForm(forms.ModelForm):
  37. custom_condition = forms.ChoiceField(
  38. required=False,
  39. label=_("Custom condition"), choices=())
  40. def __init__(self, *args, **kwargs):
  41. super(ConditionForm, self).__init__(*args, **kwargs)
  42. custom_conditions = Condition.objects.all().exclude(
  43. proxy_class=None)
  44. if len(custom_conditions) > 0:
  45. # Initialise custom_condition field
  46. choices = [(c.id, c.__unicode__()) for c in custom_conditions]
  47. choices.insert(0, ('', ' --------- '))
  48. self.fields['custom_condition'].choices = choices
  49. condition = kwargs.get('instance')
  50. if condition:
  51. self.fields['custom_condition'].initial = condition.id
  52. else:
  53. # No custom conditions and so the type/range/value fields
  54. # are no longer optional
  55. for field in ('type', 'range', 'value'):
  56. self.fields[field].required = True
  57. class Meta:
  58. model = Condition
  59. exclude = ('proxy_class',)
  60. def clean(self):
  61. data = super(ConditionForm, self).clean()
  62. # Check that either a condition has been entered or a custom condition
  63. # has been chosen
  64. if not any(data.values()):
  65. raise forms.ValidationError(
  66. _("Please either choose a range, type and value OR "
  67. "select a custom condition"))
  68. if not data['custom_condition']:
  69. if not data.get('range', None):
  70. raise forms.ValidationError(
  71. _("A range is required"))
  72. return data
  73. def save(self, *args, **kwargs):
  74. # We don't save a new model if a custom condition has been chosen,
  75. # we simply return the instance that has been chosen
  76. if self.cleaned_data['custom_condition']:
  77. return Condition.objects.get(
  78. id=self.cleaned_data['custom_condition'])
  79. return super(ConditionForm, self).save(*args, **kwargs)
  80. class BenefitForm(forms.ModelForm):
  81. custom_benefit = forms.ChoiceField(
  82. required=False,
  83. label=_("Custom incentive"), choices=())
  84. def __init__(self, *args, **kwargs):
  85. super(BenefitForm, self).__init__(*args, **kwargs)
  86. custom_benefits = Benefit.objects.all().exclude(
  87. proxy_class=None)
  88. if len(custom_benefits) > 0:
  89. # Initialise custom_benefit field
  90. choices = [(c.id, c.__unicode__()) for c in custom_benefits]
  91. choices.insert(0, ('', ' --------- '))
  92. self.fields['custom_benefit'].choices = choices
  93. benefit = kwargs.get('instance')
  94. if benefit:
  95. self.fields['custom_benefit'].initial = benefit.id
  96. else:
  97. # No custom benefit and so the type fields
  98. # are no longer optional
  99. self.fields['type'].required = True
  100. class Meta:
  101. model = Benefit
  102. exclude = ('proxy_class',)
  103. def clean(self):
  104. data = super(BenefitForm, self).clean()
  105. # Check that either a benefit has been entered or a custom benfit
  106. # has been chosen
  107. if not any(data.values()):
  108. raise forms.ValidationError(
  109. _("Please either choose a range, type and value OR "
  110. "select a custom incentive"))
  111. if data['custom_benefit']:
  112. if data.get('range') or data.get('type') or data.get('value'):
  113. raise forms.ValidationError(
  114. _("No other options can be set if you are using a "
  115. "custom incentive"))
  116. return data
  117. def save(self, *args, **kwargs):
  118. # We don't save a new model if a custom benefit has been chosen,
  119. # we simply return the instance that has been chosen
  120. if self.cleaned_data['custom_benefit']:
  121. return Benefit.objects.get(
  122. id=self.cleaned_data['custom_benefit'])
  123. return super(BenefitForm, self).save(*args, **kwargs)
  124. class OfferSearchForm(forms.Form):
  125. name = forms.CharField(required=False, label=_("Offer name"))
  126. is_active = forms.BooleanField(required=False, label=_("Is active?"))