reg/forms.py
author nishanth
Fri, 23 Apr 2010 16:36:40 +0530
changeset 99 cc2ed87ee896
parent 62 b7e47cc39342
permissions -rwxr-xr-x
resolved a bug

import string
from datetime import datetime

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth import authenticate

from ws_app.reg.models import Profile, Event, GENDER_CHOICES, PROFESSION_CHOICES

class LoginForm(forms.Form):
    """ a form to handle login.
    """

    email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput)

    def clean_email(self):
        """ see if a user exists for this email.
        """

        email = self.cleaned_data['email']
        password = self.data['password']
        try:
            username = User.objects.get(email__iexact=email).username
        except User.DoesNotExist:
            raise forms.ValidationError("Incorrect e-mail or password")

        user = authenticate(username=username, password=password)
        if not user:
            raise forms.ValidationError("Incorrect e-mail or password")
        return email

class RegisterForm(forms.ModelForm):
    """ add the fields email and password
    and then generate form using profile model.
    """

    email = forms.EmailField()
    password = forms.CharField(widget=forms.PasswordInput, help_text="Choose a good password which 8 to 30 chars long")
    confirm_password = forms.CharField(widget=forms.PasswordInput) 

    first_name = forms.CharField(required=True)
    last_name = forms.CharField()

    class Meta:
        model = Profile
        fields = ['email', 'password', 'confirm_password', 'first_name', 'last_name', 'gender', 'profession', 'affiliated_to', 'interests']

    def clean_first_name(self):
        """ firstname should contain only alphabets.
        """

        first_name = self.cleaned_data['first_name']
        if first_name.strip(string.ascii_letters):
            raise forms.ValidationError("Name must contain only alphabets")
        return first_name

    def clean_last_name(self):
        """ only alphabets allowed.
        """

        last_name = self.cleaned_data['last_name']
        if last_name.strip(string.ascii_letters):
            raise forms.ValidationError("Name must contain only alphabets")
        return last_name

    def clean_email(self):
        """ check if a user exists with same email.
        """

        email = self.cleaned_data['email']
        try:
            User.objects.get(email__iexact=email)
            raise forms.ValidationError("An account already exists with this email.\
                                        Click on forgot password if you have forgotten your password")
        except User.DoesNotExist:
            return email

    def clean_password(self):
        """ check if the password contains only alphabets or digits or punctuation.
        then check if the size of the password is optimal.
        then check if both the given passwords match.
        """

        password = self.cleaned_data['password']

        if password.strip(string.ascii_letters+string.punctuation+string.digits):
            raise forms.ValidationError("Only alphabets, digits and punctuation symbols are allowed in password")

        if not 8 <= len(password) <= 30:
            raise forms.ValidationError("Password must be atleast 8 characters and at most 30 characters")

        if not password == self.data['confirm_password']:
            raise forms.ValidationError("Passwords do not match")

        return password

class EventCreateForm(forms.ModelForm):
    """ A form to create an event.
    """

    class Meta:
        model = Event
        fields = ['title', 'description', 'start_date', 'stop_date', 'venue']

    def clean_start_date(self):
        """ see if the start date is greater than today or not.
        """

        start_date = self.cleaned_data['start_date']
        if start_date < datetime.now().date():
            raise forms.ValidationError("The event must start at the latest today.")
        return start_date

    def clean_stop_date(self):
        """ see that stop_date is not less than start_date.
        """

        stop_date = self.cleaned_data['stop_date']

        start_date = self.clean_start_date()

        if start_date > stop_date:
            raise forms.ValidationError('The event stops even before it starts. I am starting to wonder what kind of event is this.')
        return stop_date

class PasswordResetForm(forms.Form):
    """ check for the existance of user for the email.
    Reset the password irrespective of active status.
    """

    email = forms.EmailField()

    def clean_email(self):

        email = self.cleaned_data['email']
        try:
            user = User.objects.get(email__iexact=email)
            return email
        except User.DoesNotExist:
            raise forms.ValidationError("This not a registered email. Please enter a valid email.")

        return email

class PasswordChangeForm(forms.Form):

    old_password = forms.CharField(widget=forms.PasswordInput)
    new_password = forms.CharField(widget=forms.PasswordInput)
    confirm_password = forms.CharField(widget=forms.PasswordInput)

    def clean_old_password(self):
        """ authenticate the given password against username.
        """

        username = self.data['username']
        old_password = self.cleaned_data['old_password']
        user = authenticate(username=username, password=old_password)
        if not user:
            raise forms.ValidationError("Incorrect password")
        return old_password


    def clean_new_password(self):
        """ check if the password contains only alphabets or digits or punctuation.
        then check if the size of the password is optimal.
        then check if both the given passwords match.
        """

        new_password = self.cleaned_data['new_password']

        if new_password.strip(string.ascii_letters+string.punctuation+string.digits):
            raise forms.ValidationError("Only alphabets, digits and punctuation symbols are allowed in password")

        if not 8 <= len(new_password) <= 30:
            raise forms.ValidationError("Password must be atleast 8 characters and at most 30 characters")

        if not new_password == self.data['confirm_password']:
            raise forms.ValidationError("Passwords do not match")

        return new_password

class EditProfileForm(forms.Form):
    """ form for editing the profile.
    """

    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)
    gender = forms.ChoiceField(choices=GENDER_CHOICES)
    profession = forms.ChoiceField(choices=PROFESSION_CHOICES)
    affiliated_to = forms.CharField(max_length=100, required=True, label="College/Company")
    interests = forms.CharField(max_length=100, label="Fields of interest")

    def clean_first_name(self):
        """ firstname should contain only alphabets.
        """

        first_name = self.cleaned_data['first_name']
        if first_name.strip(string.ascii_letters):
            raise forms.ValidationError("Name must contain only alphabets")
        return first_name

    def clean_last_name(self):
        """ only alphabets allowed.
        """

        last_name = self.cleaned_data['last_name']
        if last_name.strip(string.ascii_letters):
            raise forms.ValidationError("Name must contain only alphabets")
        return last_name