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 1.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from django import forms
  2. class FormFactory(object):
  3. def create(self, item, values=None):
  4. """
  5. For dynamically creating add-to-basket forms for a given product
  6. """
  7. self.values = values
  8. if item.is_group:
  9. return self._create_group_product_form(item)
  10. return self._create_product_form(item)
  11. def _create_group_product_form(self, item):
  12. pass
  13. def _create_product_form(self, item):
  14. # See http://www.b-list.org/weblog/2008/nov/09/dynamic-forms/ for
  15. # advice on how this works.
  16. self.fields = {'action': forms.CharField(widget=forms.HiddenInput(), initial='add'),
  17. 'product_id': forms.IntegerField(widget=forms.HiddenInput(), min_value=1),
  18. 'quantity': forms.IntegerField(min_value=1)}
  19. if not self.values:
  20. self.values = {'action': 'add',
  21. 'product_id': item.id,
  22. 'quantity': 1}
  23. for option in item.options.all():
  24. self._add_option_field(item, option)
  25. form_class = type('AddToBasketForm', (forms.BaseForm,), {'base_fields': self.fields})
  26. return form_class(self.values)
  27. def _add_option_field(self, item, option):
  28. """
  29. Creates the appropriate form field for the product option.
  30. This is designed to be overridden so that specific widgets can be used for
  31. certain types of options.
  32. """
  33. self.fields[option.code] = forms.CharField()