Advertisement
Guest User

Untitled

a guest
Oct 12th, 2017
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 26.46 KB | None | 0 0
  1. from django import forms
  2. from django.contrib.auth.models import User
  3. from django.forms.util import ErrorList
  4. from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
  5. from django.contrib.auth import authenticate, login
  6. from django.utils.safestring import mark_safe
  7. from django.forms.models import modelformset_factory
  8. from captcha.fields import CaptchaField
  9. from django.forms.extras.widgets import SelectDateWidget
  10. from django.utils.translation import ugettext_lazy as _
  11.  
  12. import datetime
  13.  
  14. from countrysites.settings import settings as countrysettings
  15.  
  16. from models import *
  17. from basket import Basket
  18.  
  19. import re
  20.  
  21. import widgets
  22.  
  23. default_choice = [('', '----------')]
  24.  
  25. SubCategoryFormSet = modelformset_factory(SubCategory)
  26. ProductCategoryFormSet = modelformset_factory(ProductCategory)
  27.  
  28. class SAIDForm(forms.Form):
  29. id_number = forms.RegexField(regex='(((\d{2}((0[13578]|1[02])(0[1-9]|[12]\d|3[01])|(0[13456789]|1[012])(0[1-9]|[12]\d|30)|02(0[1-9]|1\d|2[0-8])))|([02468][048]|[13579][26])0229))(( |-)(\d{4})( |-)(\d{3})|(\d{7}))')
  30.  
  31. class DiscountForm(forms.Form):
  32. discount = forms.CharField(max_length=30, required=False, label="Promotional Code")
  33.  
  34. def clean_discount(self):
  35. discount = self.cleaned_data['discount'].strip()
  36.  
  37. return discount
  38.  
  39. class SalesReport(forms.Form):
  40.  
  41. # payment statuses - this should probably be migrated to the db
  42. STATUS_CHOICES = (
  43. (-1, 'all'),
  44. (0, 'Refunded'),
  45. (1, 'Voided'),
  46. (2, 'Pending'),
  47. (3, 'Failed'),
  48. (4, 'Authorised'),
  49. (5, 'Packing'),
  50. (6, 'Dispatched'),
  51. (7, 'Complete'),
  52. )
  53.  
  54. QUERY_TYPE = (
  55. ('yearly', 'Yearly'),
  56. ('monthly', 'Monthly'),
  57. ('weekly', 'Weekly'),
  58. ('daily', 'Daily'),
  59. )
  60.  
  61. RESULT_TYPE = (
  62. ('onscreen', 'On Screen'),
  63. ('csv', 'CSV (for excell)'),
  64. )
  65. # , input_formats='%d/%m/%y'
  66. start_date = forms.DateField(label="start date", input_formats=('%d/%m/%y',),initial=datetime.date.today().replace(day=1).strftime('%d/%m/%y'),required=True)
  67. end_date = forms.DateField(label="end date", input_formats=('%d/%m/%y',), initial=datetime.date.today().strftime('%d/%m/%y'),required=True)
  68. status = forms.ChoiceField(choices=STATUS_CHOICES, label="Select orders by status", initial=7)
  69. #query_type = forms.ChoiceField(choices=QUERY_TYPE, label="Results by", initial='daily')
  70. result_type = forms.ChoiceField(choices=RESULT_TYPE, label="Result type", initial='onscreen')
  71.  
  72.  
  73. class ProductCategoryForm(forms.ModelForm):
  74. """
  75. A form for the relationship between products and their parent categories
  76. """
  77. class Meta:
  78. model = ProductCategory
  79.  
  80. class ProductForm(forms.ModelForm):
  81. """
  82. A form for the editing of a shop product
  83. """
  84. class Meta:
  85. model = Product
  86.  
  87. class CategoryForm(forms.ModelForm):
  88. """
  89. A form for the editing of a shop category
  90. """
  91. class Meta:
  92. model = Category
  93.  
  94. class RegisterAccountForm(forms.ModelForm):
  95. """
  96. A form with most of the fields needed for registering an account.
  97. Note that this form is different to the UpdateAccountForm form because
  98. it doesn't allow the ability to change addresses (purely because the user
  99. won't yet have any at registration point). Also assumes that the customer
  100. must agree to some terms and conditions at registration.
  101. """
  102. # tsandcs = forms.BooleanField(help_text="I agree to the Terms and Conditions below",error_messages={'required': 'You must agree to the Terms and Conditions'})
  103. #captcha = CaptchaField(label="Verification Code")
  104.  
  105. class Meta:
  106. model = Account
  107. exclude = ('user','default_address','temporary','dob','gender','malinglist','informed','security_question')
  108.  
  109. ''' class QuickPayAccountForm(forms.ModelForm):
  110. """ """
  111. A form with most of the fields needed for registering an account ergo just
  112. for the sake of ergo.
  113. Note that this form is different to the UpdateAccountForm form because
  114. it doesn't allow the ability to change addresses (purely because the user
  115. won't yet have any at registration point). Also assumes that the customer
  116. must agree to some terms and conditions at registration.
  117. """ """
  118. # tsandcs = forms.BooleanField(help_text="I agree to the Terms and Conditions below",error_messages={'required': 'You must agree to the Terms and Conditions'})
  119. #captcha = CaptchaField(label="Verification Code")
  120.  
  121. class Meta:
  122. model = Account
  123. exclude = ('user','default_address','temporary','security_question','security_answer','feedback')
  124.  
  125. class UpdateAccountForm(forms.ModelForm):
  126. """ """
  127. Partnering RegisterAccountForm, this version allows the editing of both
  128. address fields and insists that the 'instance' keyword is supplied to the
  129. constructor, indicating an update. Builds the list of address choices
  130. dynamically, from those assigned to the related account.
  131. """ """
  132. class Meta:
  133. model = Account
  134. exclude = ('user','temporary')
  135.  
  136. def __init__(self, *args, **kwargs):
  137. """ """
  138. Set the address choices for this account to be those that already exist
  139. against the account
  140. """ """
  141. super(UpdateAccountForm, self).__init__(*args, **kwargs)
  142. if not 'instance' in kwargs:
  143. raise TypeError("UpdateAccountForm requires keyword paramter 'instance'")
  144.  
  145. address_choices = [(address.id, str(address)) for address in kwargs['instance'].address_set.all()]
  146. self.fields['default_address'].choices = address_choices
  147.  
  148. class LoginForm(forms.Form):
  149. """ """
  150. A helper form for logging in customers. This form actually performs a log in
  151. when clean is called, assuming the email and password combination is valid.
  152. """ """
  153. email = forms.EmailField()
  154. password = forms.CharField(widget=forms.PasswordInput,min_length=5)
  155.  
  156. def __init__(self, request, data=None, files=None, auto_id='id_%s', prefix=None,
  157. initial=None, error_class=ErrorList, label_suffix=':',
  158. empty_permitted=False):
  159. """ """
  160. Save a reference to the request object on this instance
  161. """ """
  162. super(LoginForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted)
  163. self.request = request
  164.  
  165. def clean(self):
  166. """ """
  167. Process the log in request. If both email and password data has been
  168. entered, this function first tries to retrieve a matching account
  169. object from the database which is both persistent and non-staff. If
  170. successful, the username is passed through the django authenticate
  171. mechanism to check whether the username and password is correct.
  172. """ """
  173. cleaned_data = self.cleaned_data
  174. email = cleaned_data.get('email')
  175. password = cleaned_data.get('password')
  176.  
  177. if email and password:
  178. try:
  179. user = Account.objects.get(user__email=email, user__is_staff=False, temporary=False).user
  180. except ObjectDoesNotExist:
  181. raise forms.ValidationError("No customer exists with that email address")
  182. except MultipleObjectsReturned:
  183. raise forms.ValidationError("Unfortunately, there seems to be an issue. We have two accounts with that email address and cannot log you in! "
  184. "This should not happen and is likely a bug with our software. Please get in touch and notify us of this issue.")
  185. user = authenticate(username=user.username, password=password)
  186. if user is not None:
  187. if user.is_active:
  188. login(self.request, user)
  189. else:
  190. # Possibly email admin here to notify of attempted access to locked account
  191. raise forms.ValidationError("Your account has been temporarily locked.")
  192. else:
  193. raise forms.ValidationError("The password for that account is incorrect")
  194. self.user = user
  195.  
  196. return cleaned_data
  197. '''
  198. class DiscountCodeForm(forms.Form):
  199. """
  200. A form that allows the customer to enter a discount code on their basket.
  201. The clean method implements the logic that inserts the discount on to the
  202. basket, if the offer code validates
  203. """
  204. discount_code = forms.CharField(label=_("Discount Code:"), required=False)
  205. ''' def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
  206. initial=None, error_class=ErrorList, label_suffix=':',
  207. empty_permitted=False):
  208. """
  209. If the customer has already set a discount code, then populate it's
  210. initial value correctly on the form
  211. """
  212.  
  213. super(DiscountCodeForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted)
  214.  
  215. #discount = basket.discount
  216. #if discount:
  217. # self.fields['discount_code'].initial = discount.code
  218.  
  219. def clean(self):
  220. """
  221. Validate that the discount code being passed to this form exists in
  222. the database.
  223. """
  224. cleaned_data = self.cleaned_data
  225.  
  226. #discount_code = cleaned_data.get('discount_code')
  227.  
  228. #if discount_code:
  229. # try:
  230. # offer = Offer.objects.get(public=True,code=discount_code)
  231. # except ObjectDoesNotExist, MultipleObjectsReturned:
  232. # self._errors["discount_code"] = ErrorList([u"Discount code not found"])
  233.  
  234. #return '' #cleaned_data '''
  235.  
  236. class BasketRowForm(forms.Form):
  237. """
  238. A form that allows quantities to be updated per row on the basket. This
  239. allows for the change of quantities and the deletion of the row entirely
  240. via the checkbox
  241. """
  242. operate = forms.BooleanField(required=False)
  243. quantity = forms.IntegerField(required=False,min_value=0)
  244.  
  245. def __init__(self, basket_item, data=None, files=None, auto_id='id_%s', initial=None,
  246. error_class=ErrorList, label_suffix=':', empty_permitted=False):
  247. """
  248. Change the initial value of this row's quantity field to be the value
  249. in the basket row.
  250. """
  251. prefix = basket_item.item.id
  252. super(BasketRowForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted)
  253. self.fields['quantity'].initial = basket_item.quantity
  254. '''
  255. class PasswordResetForm(forms.Form):
  256. """
  257. This form provides validation for the second step of the password reset
  258. process. It validates valid passwords and that the answer is valid for the
  259. given user's question
  260. """
  261. answer = forms.CharField()
  262. new_password = forms.CharField(widget=forms.PasswordInput,min_length=5)
  263. confirm_password = forms.CharField(widget=forms.PasswordInput,min_length=5)
  264.  
  265. def __init__(self, password_request, data=None, files=None, auto_id='id_%s', prefix=None,
  266. initial=None, error_class=ErrorList, label_suffix=':',
  267. empty_permitted=False):
  268. """
  269. Set the label of the answer field to be the question that the customer
  270. selected and store a reference to the password request object in this
  271. instance
  272. """
  273. super(PasswordResetForm, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted)
  274. self.fields['answer'].label = str(password_request.account.security_question)
  275. self.password_request = password_request
  276.  
  277. def clean(self):
  278. """
  279. Ensure that the new passwords being chosen match and that the answer
  280. is correct for this customer's chosen question. Also ensure that the
  281. associated password request is still in-date and valid
  282. """
  283. cleaned_data = self.cleaned_data
  284.  
  285. new_password = cleaned_data.get("new_password")
  286. confirm_password = cleaned_data.get("confirm_password")
  287.  
  288. if new_password != confirm_password:
  289. self._errors["new_password"] = ErrorList([u"Your passwords did not match"])
  290.  
  291. answer = cleaned_data.get('answer')
  292.  
  293. if answer:
  294. if str(answer).lower() != str(self.password_request.account.security_answer).lower():
  295. self._errors["answer"] = ErrorList([u"This answer is incorrect"])
  296.  
  297. if not self.password_request.is_valid():
  298. raise forms.ValidationError("This password reset request is no longer valid.")
  299.  
  300. return cleaned_data
  301.  
  302. class ForgottenPasswordForm(forms.Form):
  303. """
  304. The first step in the forgotten password process. Requests that you enter
  305. your email address and complete a captcha. On success, an email should be
  306. sent out with a link to the second stage of this process
  307. """
  308. email = forms.EmailField()
  309. #captcha = CaptchaField(label="Verification Code")
  310.  
  311. def clean(self):
  312. """
  313. Provide validation that the email being entered exists in the database
  314. for a persistent store account
  315. """
  316. cleaned_data = self.cleaned_data
  317. email = cleaned_data.get('email')
  318.  
  319. if email:
  320. try:
  321. user = Account.objects.get(user__email=email, user__is_staff=False, temporary=False)
  322. except ObjectDoesNotExist:
  323. raise forms.ValidationError("No customer exists with that email address")
  324. except MultipleObjectsReturned:
  325. raise forms.ValidationError("Unfortunately, there seems to be an issue. We have two accounts with that email address and cannot retreive a password! "
  326. "This should not happen and is likely a bug with our software. Please get in touch and notify us of this issue.")
  327. return cleaned_data
  328. '''
  329. class AddressForm(forms.ModelForm):
  330. """
  331. Add new addresses. It is assumed that when adding an address, the customer
  332. will be logged in, so we don't want, or need, them to choose the related
  333. account. This will come from session data.
  334. """
  335.  
  336. country = forms.ModelChoiceField(queryset=Country.objects,widget=widgets.SelectCountry)
  337.  
  338. class Meta:
  339. model = Address
  340. exclude = ('account',)
  341.  
  342. def __init__(self, *args, **kwargs):
  343. super(AddressForm, self).__init__(*args, **kwargs)
  344. self.fields['country'].initial = 1
  345. if countrysettings.country == 'me':
  346. self.fields['county'].label = 'State'
  347. self.fields['postcode'].required = False
  348. else:
  349. self.fields['postcode'].required = True
  350.  
  351. class AddressForm_me(forms.ModelForm):
  352. """
  353. Add new addresses. It is assumed that when adding an address, the customer
  354. will be logged in, so we don't want, or need, them to choose the related
  355. account. This will come from session data.
  356. """
  357.  
  358. country = forms.ModelChoiceField(queryset=Country.objects,widget=widgets.SelectCountry)
  359.  
  360. class Meta:
  361. model = Address_me
  362. exclude = ('account',)
  363.  
  364. def __init__(self, *args, **kwargs):
  365. super(AddressForm_me, self).__init__(*args, **kwargs)
  366. self.fields['country'].initial = 1
  367.  
  368.  
  369. '''
  370. class DeliveryOptions(forms.Form):
  371. """
  372. Choose your delivery method! Also provides an extra information box if the
  373. customer wishes to provide extra delivery instructions
  374. """
  375. method = forms.ChoiceField(widget=forms.RadioSelect(),error_messages={'required': 'Please select a shipping option.'})
  376. information = forms.CharField(widget=forms.Textarea(),required=False)
  377.  
  378. def has_choices(self):
  379. """
  380. Return True if the number of shipping methods available to the customer
  381. is at least one. False otherwise.
  382. """
  383. return len(self.fields['method'].choices) > 0
  384.  
  385. def num_choices(self):
  386. """
  387. Return the number of shipping methods available in the customers chosen
  388. region
  389. """
  390. return len(self.fields['method'].choices)
  391.  
  392. def method_choices(self):
  393. """
  394. Return the choices available for the shipping method, this will be
  395. returned as a list of 2-item tuples
  396. """
  397. return self.fields['method'].choices
  398.  
  399. def __init__(self, account, basket, data=None, files=None, auto_id='id_%s', prefix=None,
  400. initial=None, error_class=ErrorList, label_suffix=':',
  401. empty_permitted=False):
  402. """
  403. If the customer has already chosen a delivery method then set the method
  404. default to that chosen method, also, pre-populate the information field
  405. if the customer has already specified some delivery instructions
  406. """
  407. super(DeliveryOptions, self).__init__(data, files, auto_id, prefix, initial, error_class, label_suffix, empty_permitted)
  408.  
  409. if basket.delivery_address:
  410. bands = basket.delivery_address.country.zone.band_set.all()
  411. self.fields['method'].choices = ((band.postage.id, mark_safe(band.display_line(account))) for band in bands)
  412.  
  413. if basket.postage:
  414. self.fields['method'].initial = basket.postage.id
  415.  
  416. if basket.delivery_instructions:
  417. self.fields['information'].initial = basket.delivery_instructions
  418.  
  419. class AddressSelectForm(forms.ModelForm):
  420. """
  421. Select the address you want the item shipping to. It is assumed that when
  422. adding an address, the customer will be logged in, so we don't want, or
  423. need, them to choose the related account. This will come from session data.
  424. """
  425. existing_address = forms.ChoiceField(label="Existing addresses", widget=forms.RadioSelect(), required=False)
  426.  
  427. class Meta:
  428. model = Address
  429. exclude = ('account',)
  430.  
  431. def __init__(self, *args, **kwargs):
  432. """
  433. Store references to the account and basket that should be passed to this
  434. form as keyword parameters (account, basket).
  435. """
  436. self.account = kwargs.pop('account')
  437. self.basket = kwargs.pop('basket')
  438. super(AddressSelectForm, self).__init__(*args, **kwargs)
  439.  
  440. value = self.fields.pop('existing_address')
  441. self.fields.insert(0, 'existing_address', value)
  442.  
  443. self.refresh_address_options()
  444.  
  445. def refresh_address_options(self):
  446. """
  447. Generate a new list of valid addresses for this customer.
  448. """
  449. default_addr = None
  450.  
  451. if self.basket.delivery_address:
  452. default_addr = self.basket.delivery_address.id
  453. elif self.account.default_address:
  454. default_addr = self.account.default_address.id
  455.  
  456. addresses = [(addr.id,mark_safe("<br/>".join(addr.line_list()))) for addr in self.account.address_set.all()] + [('','Use Another')]
  457.  
  458. self.fields['existing_address'].choices = addresses
  459. self.fields['existing_address'].initial = default_addr
  460.  
  461. def clean(self):
  462. """
  463. Remove all errors related to the existing_address field. They won't be
  464. valid anyway
  465. """
  466. cleaned_data = self.cleaned_data
  467.  
  468. if cleaned_data.get("existing_address"):
  469. for k, v in self._errors.items():
  470. del self._errors[k]
  471.  
  472. return cleaned_data
  473.  
  474. class QuickPayUserForm(forms.ModelForm):
  475. """
  476. A base User form that implements logic for ensuring that the email being
  477. used is not already used by a persistent account. It will however allow a
  478. registration for a duplicate email address if that email is only used by
  479. temporary account holders!
  480. Unlike the account forms, which are separated into two distinct classes,
  481. the UserForm class takes a keyword parameter in it's constructor, which,
  482. if True, tells the class to apply validation as if it were an
  483. update, rather than an insertion. This lets us ignore email collisions in
  484. the user table.
  485. """
  486.  
  487. class Meta:
  488. model = User
  489. fields = ('first_name','last_name','email')
  490.  
  491. def __init__(self, *args, **kwargs):
  492. """
  493. Make it so that first name, last name and email addresses are required
  494. inputs, even though they're allowed to be blank in the User class
  495. Django provides
  496. """
  497. super(QuickPayUserForm, self).__init__(*args, **kwargs)
  498.  
  499. self.update = 'instance' in kwargs
  500.  
  501. # We really need this data
  502. self.fields['first_name'].required = True
  503. self.fields['last_name'].required = True
  504. self.fields['email'].required = True
  505.  
  506. def clean(self):
  507. """
  508. Check that the email address being used is not already taken by a
  509. permanent member of the site
  510. """
  511. cleaned_data = self.cleaned_data
  512.  
  513. email = cleaned_data.get('email')
  514.  
  515. clashes = Account.objects.filter(user__email=email, user__is_staff=False, temporary=False)
  516.  
  517. if self.update:
  518. clashes = clashes.exclude(user__id=self.instance.id)
  519.  
  520. if clashes.count():
  521. self._errors["email"] = ErrorList([u"A customer with that email address already exists"])
  522.  
  523. return cleaned_data
  524.  
  525. class UserForm(QuickPayUserForm):
  526. """
  527. A extension of the QuickPayUserForm. This form also deals with passwords
  528. because we're now concerning ourself with persistant users rather than
  529. temporary ones.
  530. """
  531. password = forms.CharField(widget=forms.PasswordInput,min_length=5)
  532. confirm_password = forms.CharField(widget=forms.PasswordInput,min_length=5)
  533.  
  534. def __init__(self, *args, **kwargs):
  535. """
  536. Make it so that the password and confirm_password fields are not
  537. required if we're performing an update rather than an insert on the
  538. User
  539. """
  540. super(UserForm, self).__init__(*args, **kwargs)
  541.  
  542. if self.update:
  543. self.fields['password'].required = False
  544. self.fields['confirm_password'].required = False
  545.  
  546. def clean(self):
  547. """
  548. Check that the passwords match
  549. """
  550. super(UserForm, self).clean()
  551.  
  552. cleaned_data = self.cleaned_data
  553.  
  554. password = cleaned_data.get("password")
  555. confirm_password = cleaned_data.get("confirm_password")
  556.  
  557. self.set_password = password and confirm_password
  558. if self.set_password and password != confirm_password:
  559. self._errors["password"] = ErrorList([u"Your passwords did not match"])
  560.  
  561. return cleaned_data
  562. '''
  563. CARD_TYPES = (
  564. (0, 'VISA', 'Visa'),
  565. (1, 'MC', 'Master Card'),
  566. (2, 'DELTA', 'Delta'),
  567. (3, 'SOLO', 'Solo'),
  568. (4, 'MAESTRO', 'Maestro / Switch'),
  569. (5, 'UKE', 'Visa Electron'),
  570. # (6, 'JCB', 'JCB'),
  571. #(7, 'AMEX', 'Amex'),
  572. # (8, 'DC', 'Diners Club'),
  573. )
  574.  
  575. CARD_TYPES_CHOICES = [(aid, adesc) for aid, vpsid, adesc in CARD_TYPES]
  576.  
  577. class PaymentForm(forms.Form):
  578. """
  579. A payment form that requests credit card details off the customer
  580. for forwarding on to payment gateways such as protx
  581. """
  582.  
  583. card_holder = forms.CharField(label=_('Name on Card'), max_length=300)
  584. card_number = forms.RegexField(label=_('Card Number'), max_length=26, regex=r'^[0-9\ ]{12,26}$', error_messages={'invalid': _('Please enter a valid card number')})
  585.  
  586. expiry_month = forms.IntegerField(label='MM', min_value=1, max_value=12, widget=forms.TextInput(attrs={'size': '3', 'maxlength': '2'}))
  587. expiry_year = forms.IntegerField(label='YY', min_value=1, max_value=99, widget=forms.TextInput(attrs={'size': '3', 'maxlength': '2'}))
  588.  
  589. ccv = forms.CharField(label=_('Security Number'), widget=forms.TextInput(attrs={'size': '5', 'maxlength': '4'}))
  590. card_type = forms.ChoiceField(label=_('Card Type'), widget=forms.Select, choices=CARD_TYPES_CHOICES)
  591.  
  592. start_month = forms.IntegerField(required=False, label='MM', min_value=1, max_value=12, widget=forms.TextInput(attrs={'size': '3', 'maxlength': '2'}))
  593. start_year = forms.IntegerField(required=False, label='YY', min_value=1, max_value=99, widget=forms.TextInput(attrs={'size': '3', 'maxlength': '2'}))
  594.  
  595. issue_number = forms.CharField(required=False, label=_('Issue Number'), widget=forms.TextInput(attrs={'size': '3', 'maxlength': '3'}))
  596.  
  597. def clean(self):
  598. """
  599. Remove white spaces from the card number
  600. """
  601. cleaned_data = self.cleaned_data
  602.  
  603. if 'card_number' in cleaned_data:
  604. cleaned_data['card_number'] = re.sub("\s+", "", cleaned_data['card_number'])
  605.  
  606. return cleaned_data
  607. class BuyerForm(forms.ModelForm):
  608. """
  609. A payment form that requests credit card details off the customer
  610. for forwarding on to payment gateways such as protx
  611. """
  612. class Meta:
  613. model = User
  614. fields = ('first_name','last_name','email')
  615. #exclude = ('is_staff','is_active','last_login','date_joined','username','password','user_permissions','groups','is_superuser')
  616.  
  617. first_name = forms.CharField(label=_('First name'), max_length=200,required=True)
  618. last_name = forms.CharField(label=_('Surname'), max_length=200,required=True)
  619. #dob = forms.DateField(label='DOB', widget=SelectDateWidget(years=range(2006,1900,-1)))
  620. #gender = forms.CharField(label='Gender', widget=forms.RadioSelect(choices=(('Male','Male'),('Female','Female'))), required=True)
  621. #phone = forms.CharField(label='Phone number', max_length=50,required=True)
  622. email = forms.EmailField(label=_('Email'), max_length=500,required=True)
  623.  
  624. def clean(self):
  625. cleaned_data = self.cleaned_data
  626. return cleaned_data
  627.  
  628. class AccountForm(forms.ModelForm):
  629. """
  630. A payment form that requests credit card details off the customer
  631. for forwarding on to payment gateways such as protx
  632. """
  633. class Meta:
  634. model = Account
  635. fields = ('dob','gender','telephone')
  636. #exclude = ('is_staff','is_active','last_login','date_joined','username','password','user_permissions','groups','is_superuser')
  637.  
  638. dob = forms.DateField(label=_('DOB'), widget=SelectDateWidget(years=range(2006,1900,-1)))
  639. gender = forms.CharField(label=_('Gender'), widget=forms.RadioSelect(choices=(('Male',_('Male')),('Female',_('Female')))), required=True)
  640. telephone = forms.CharField(label=_('Phone number'), max_length=50,required=True)
  641.  
  642. def clean(self):
  643. cleaned_data = self.cleaned_data
  644. return cleaned_data
  645.  
  646.  
  647. class TermsForm(forms.Form):
  648.  
  649. # informed = forms.BooleanField(label='Keeping you informed',required=False)
  650. mailing = forms.BooleanField(label=_('Add to mailing list'),required=False)
  651. terms = forms.BooleanField(label=_('I accept the T&C\'s'), required=True)
  652.  
  653. def clean(self):
  654. """
  655. Remove white spaces from the card number
  656. """
  657. cleaned_data = self.cleaned_data
  658.  
  659.  
  660. return cleaned_data
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement