forms.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. from django import forms
  2. from django.contrib.auth.models import User
  3. from django.core.exceptions import ValidationError
  4. from django.utils.translation import ugettext_lazy as _
  5. from .models import Idea, IdeaComment
  6. class SignUpForm(forms.Form):
  7. '''
  8. Each field (both passwords at once in their case) is checked with it's own function as
  9. by doing so all can be checked at once for errors and have errors thrown simultaneously.
  10. If the user happens to enter an email that already exists as well as a username that already
  11. exists and the two passwords don't match, then the user will be notified of all three errors
  12. without having to perform three correct_error - submit - read_error cycles
  13. '''
  14. name = forms.CharField()
  15. email = forms.EmailField()
  16. password = forms.CharField(max_length = 50, min_length = 8, widget = forms.PasswordInput)
  17. password2 = forms.CharField(max_length = 50, min_length = 8, widget = forms.PasswordInput)
  18. # clean passwords, two fields can't be declared as above
  19. def clean(self):
  20. cleanName = self.cleaned_data['name']
  21. nameExists = User.objects.filter(username = cleanName).count()
  22. if nameExists > 0 :
  23. raise ValidationError(_('Username already exists. Please try a different one.'))
  24. mail = self.cleaned_data['email']
  25. emailExists = User.objects.filter(email = mail).count()
  26. if emailExists > 0 :
  27. raise ValidationError(_('An account already exists with the email provided. Please use a different email address, or log in.'))
  28. p1 = self.cleaned_data.get('password')
  29. p2 = self.cleaned_data.get('password2')
  30. if (p1 != p2):
  31. raise ValidationError(_('Passwords do not match.'))
  32. return self.cleaned_data
  33. class AddUserForm(forms.Form):
  34. name = forms.CharField()
  35. def clean(self):
  36. cleanName = self.cleaned_data['name']
  37. nameExists = User.objects.filter(username = cleanName).count()
  38. if nameExists == 0 :
  39. raise ValidationError(_('Username does not exist. Are you sure you spelled it correctly?'))
  40. return self.cleaned_data
  41. class IdeaForm(forms.ModelForm):
  42. class Meta:
  43. model = Idea
  44. fields = ('text',)
  45. labels = {
  46. 'text': '',
  47. }
  48. widgets = {
  49. 'text': forms.Textarea(attrs = {'cols': 25})
  50. }
  51. class CommentForm(forms.ModelForm):
  52. class Meta:
  53. model = IdeaComment
  54. fields = ('text',)
  55. labels = {
  56. 'text': '',
  57. }
  58. widgets = {
  59. 'text': forms.Textarea(attrs = {'cols': 40, 'rows': 3})
  60. }