/blprofile/forms.py

https://bitbucket.org/cavneb/busylissy · Python · 126 lines · 90 code · 27 blank · 9 comment · 10 complexity · c4bdc257a6ba9f5cf0b949ce3e30b482 MD5 · raw file

  1. from django import forms
  2. from django.forms import ModelForm
  3. from django.contrib.auth.models import User
  4. from django.db.models import get_model
  5. from django.utils.translation import ugettext as _
  6. from django.core.mail import send_mail
  7. from django.template import loader, Context
  8. from django.contrib.contenttypes.models import ContentType
  9. import re
  10. from busylissy.blprofile.models import UserProfile
  11. from django.contrib.auth.models import User
  12. attrs_dict = {'class': 'required' }
  13. alnum_re = re.compile(r'^[- \w]+$')
  14. alnum_multi_re = re.compile(r'^[- ,\w]+$')
  15. class ProfileForm(ModelForm):
  16. first_name = forms.RegexField(regex=alnum_re,
  17. error_messages={'invalid':_(u'Can only contain letters, numbers and spaces')},
  18. max_length=30,
  19. min_length=3,
  20. widget=forms.TextInput(attrs=attrs_dict),
  21. label=_(u'First name'))
  22. last_name = forms.RegexField(regex=alnum_re,
  23. error_messages={'invalid':_(u'Can only contain letters, numbers and spaces')},
  24. max_length=30,
  25. min_length=3,
  26. widget=forms.TextInput(attrs=attrs_dict),
  27. label=_(u'Last name'))
  28. email = forms.EmailField(widget=forms.TextInput(attrs=dict(attrs_dict,
  29. max_length=75)),
  30. label=_(u'Email'))
  31. class Meta:
  32. model = UserProfile
  33. exclude = ('user', )
  34. fields = ['first_name', 'last_name', 'email', 'website', 'about_me', 'avatar', ]
  35. def save(self, user, force_insert=False, force_update=False, commit=True):
  36. profile = super(ProfileForm, self).save(commit=False)
  37. user.first_name = self.cleaned_data['first_name']
  38. user.last_name = self.cleaned_data['last_name']
  39. user.email = self.cleaned_data['email']
  40. user.save()
  41. profile.user = user
  42. if commit:
  43. profile.save()
  44. return profile
  45. class SettingsForm(ModelForm):
  46. class Meta:
  47. model = UserProfile
  48. fields = ['notifications', 'is_public', 'language']
  49. class MemberForm(forms.Form):
  50. username = forms.RegexField(regex=alnum_multi_re,
  51. error_messages={'invalid':_(u'Username contains only letters and numbers')},
  52. widget=forms.TextInput(attrs=attrs_dict),
  53. label=_(u'username'))
  54. def clean_username(self):
  55. """
  56. Validation of the username
  57. - user must be existent
  58. """
  59. if self.cleaned_data['username'].strip()[-1:] == ",":
  60. self.cleaned_data['username'] = self.cleaned_data['username'].strip()[:-1]
  61. usernames = self.cleaned_data['username'].split(",")
  62. error = False
  63. for username in usernames:
  64. try:
  65. user = User.objects.get(username__iexact=username.strip())
  66. except User.DoesNotExist:
  67. error = True
  68. if error:
  69. if len(usernames) > 1:
  70. error_message = _("One of the usernames does not exist")
  71. else: error_message = _("Username does not exist")
  72. raise forms.ValidationError(error_message)
  73. else:
  74. return self.cleaned_data['username']
  75. def save(self, model, model_id):
  76. instance = model.objects.get(pk=model_id)
  77. ctype = ContentType.objects.get_for_model(instance)
  78. usernames = self.cleaned_data['username'].split(",")
  79. for username in usernames:
  80. member = User.objects.get(username__iexact=username.strip())
  81. #try:
  82. # Check if invite exist
  83. #except Invite.DoesNotExist:
  84. # if member not in instance.members.all():
  85. # Send notification
  86. return usernames
  87. class InviteForm(forms.Form):
  88. email = forms.EmailField(label=_(u'email address'))
  89. def save(self, user, model, model_id, force_insert=False, force_update=False, commit=True):
  90. template = loader.get_template('blprofile/invite.txt')
  91. instance = model.objects.get(pk=model_id)
  92. context = Context({'email': self.cleaned_data['email'],
  93. 'instance': instance,
  94. 'user': user})
  95. subject = _('BusyLissy: Invite for') + " " +instance.name
  96. message = template.render(context)
  97. invite_email = self.cleaned_data['email']
  98. send_mail(subject, message, user.email, [invite_email,])
  99. return invite_email