/myapp/forms.py

https://github.com/domeav/Lady-Penh · Python · 104 lines · 90 code · 4 blank · 10 comment · 2 complexity · a26d11fadd3b8db0d4097dce07ddf1d4 MD5 · raw file

  1. # -*- coding: utf-8 -*-
  2. from django import forms
  3. from django.contrib.auth.models import User
  4. from django.core.files.uploadedfile import UploadedFile
  5. from django.utils.translation import ugettext_lazy as _, ugettext as __
  6. from myapp.models import Person, File, Contract
  7. from ragendja.auth.models import UserTraits
  8. from ragendja.forms import FormWithSets, FormSetField
  9. from registration.forms import RegistrationForm, RegistrationFormUniqueEmail
  10. from registration.models import RegistrationProfile
  11. class UserRegistrationForm(forms.ModelForm):
  12. username = forms.RegexField(regex=r'^\w+$', max_length=30,
  13. label=_(u'Username'))
  14. email = forms.EmailField(widget=forms.TextInput(attrs=dict(maxlength=75)),
  15. label=_(u'Email address'))
  16. password1 = forms.CharField(widget=forms.PasswordInput(render_value=False),
  17. label=_(u'Password'))
  18. password2 = forms.CharField(widget=forms.PasswordInput(render_value=False),
  19. label=_(u'Password (again)'))
  20. def clean_username(self):
  21. """
  22. Validate that the username is alphanumeric and is not already
  23. in use.
  24. """
  25. user = User.get_by_key_name("key_"+self.cleaned_data['username'].lower())
  26. if user and user.is_active:
  27. raise forms.ValidationError(__(u'This username is already taken. Please choose another.'))
  28. return self.cleaned_data['username']
  29. def clean(self):
  30. """
  31. Verifiy that the values entered into the two password fields
  32. match. Note that an error here will end up in
  33. ``non_field_errors()`` because it doesn't apply to a single
  34. field.
  35. """
  36. if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
  37. if self.cleaned_data['password1'] != self.cleaned_data['password2']:
  38. raise forms.ValidationError(__(u'You must type the same password each time'))
  39. return self.cleaned_data
  40. def save(self, domain_override=""):
  41. """
  42. Create the new ``User`` and ``RegistrationProfile``, and
  43. returns the ``User``.
  44. This is essentially a light wrapper around
  45. ``RegistrationProfile.objects.create_inactive_user()``,
  46. feeding it the form data and a profile callback (see the
  47. documentation on ``create_inactive_user()`` for details) if
  48. supplied.
  49. """
  50. new_user = RegistrationProfile.objects.create_inactive_user(
  51. username=self.cleaned_data['username'],
  52. password=self.cleaned_data['password1'],
  53. email=self.cleaned_data['email'],
  54. domain_override=domain_override)
  55. self.instance = new_user
  56. return super(UserRegistrationForm, self).save()
  57. def clean_email(self):
  58. """
  59. Validate that the supplied email address is unique for the
  60. site.
  61. """
  62. email = self.cleaned_data['email'].lower()
  63. if User.all().filter('email =', email).filter(
  64. 'is_active =', True).count(1):
  65. raise forms.ValidationError(__(u'This email address is already in use. Please supply a different email address.'))
  66. return email
  67. class Meta:
  68. model = User
  69. exclude = UserTraits.properties().keys()
  70. class FileForm(forms.ModelForm):
  71. name = forms.CharField(required=False, label='Name (set automatically)')
  72. def clean(self):
  73. file = self.cleaned_data.get('file')
  74. if not self.cleaned_data.get('name'):
  75. if isinstance(file, UploadedFile):
  76. self.cleaned_data['name'] = file.name
  77. else:
  78. del self.cleaned_data['name']
  79. return self.cleaned_data
  80. class Meta:
  81. model = File
  82. class PersonForm(forms.ModelForm):
  83. files = FormSetField(File, form=FileForm, exclude='content_type')
  84. employers = FormSetField(Contract, fk_name='employee')
  85. employees = FormSetField(Contract, fk_name='employer')
  86. class Meta:
  87. model = Person
  88. PersonForm = FormWithSets(PersonForm)