forms.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. """ Checkout forms """
  2. from django import forms
  3. from store_order.models import Order
  4. import re
  5. def strip_non_numbers(data):
  6. """ gets rid of all non-number characters """
  7. non_numbers = re.compile(r"\D")
  8. return non_numbers.sub("", data)
  9. # Currently not used, can remove if we don't need in future
  10. class CheckoutForm(forms.ModelForm):
  11. """ checkout form class to collect user billing and
  12. shipping information for placing an order """
  13. def __init__(self, *args, **kwargs):
  14. super(CheckoutForm, self).__init__(*args, **kwargs)
  15. # override default attributes
  16. for field in self.fields:
  17. self.fields[field].widget.attrs["size"] = "30"
  18. self.fields["shipping_state"].widget.attrs["size"] = "3"
  19. self.fields["billing_state"].widget.attrs["size"] = "3"
  20. self.fields["billing_zip"].widget.attrs["size"] = "6"
  21. class Meta:
  22. model = Order
  23. exclude = ("status", "ip_address", "user", "transaction_id")
  24. def clean_phone(self):
  25. """ Validate the phone field """
  26. phone = self.cleaned_data["phone"]
  27. stripped_phone = strip_non_numbers(phone)
  28. if len(stripped_phone) < 10:
  29. error_str = (
  30. "Enter a valid phone number with area code." "(e.g. 555-555-5555)"
  31. )
  32. raise forms.ValidationError(error_str)
  33. return self.cleaned_data["phone"]