reg/forms.py
author nishanth
Mon, 12 Apr 2010 02:57:25 +0530
changeset 9 e29ecb7819e7
parent 8 e2699e042129
child 17 125b6fc8f20b
permissions -rw-r--r--
password change and password reset have been done.

import string
from datetime import datetime

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

from workshop.reg.models import Profile, Event

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_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")

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

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

    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']
        try:
            start_date = datetime.strptime(self.data['start_date'], "%Y-%m-%d").date()
        except ValueError:
            raise forms.ValidationError("Enter a valid 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.")

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")