sdi/forms.py
author nishanth
Mon, 26 Jul 2010 17:44:26 +0530
branchanoop
changeset 175 b48d4c18a0aa
parent 133 38b7bad92b5b
child 234 cf3de6d222ce
permissions -rw-r--r--
created form for sending accomodation info

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

from sage_days.sdi.models import Registrant, TOPICS_CHOICES, ParticipantInfo, SPRINT_CHOICES
from captcha.fields import CaptchaField

class RegisterForm(forms.ModelForm):
    """ The form that is displayed to user.
    """

    topics_interested = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=TOPICS_CHOICES, required=False)
    class Meta:
        model = Registrant
        exclude = ['priority_for_attending', 'selected_for_attending']
    verification_code = CaptchaField()

    def clean_email(self):
        """ See if the user has already registered using the email.
        """

        email = self.cleaned_data['email'].strip()
        try:
            Registrant.objects.get(email__iexact=email)
            raise forms.ValidationError("This email is already registered. Did you register earlier??")
        except Registrant.DoesNotExist:
            return email

    def clean_topics_interested(self):
        """ Join the choices using PIPE character and store them.
        """

        topics = self.cleaned_data['topics_interested']
        return "|".join(topics)

class SearchForm(forms.Form):
    """ Search form for filtering registrants.
    """

    topics_interested = forms.CharField(required=False, help_text=" Use numbers seperated by spaces and prefix a minus to exclude")
    knowledge_of_python = forms.CharField(required=False, help_text=" Give single number from 1 to 5 or a range seperated by hyphen")
    knowledge_of_sage = forms.CharField(required=False, help_text=" Give single number from 1 to 5 or a range seperated by hyphen")
    likeliness_of_attending = forms.CharField(required=False, help_text=" Give single number from 1 to 5 or a range seperated by hyphen")
    #need_for_python_workshop = forms.BooleanField(required=False)
    #need_accomodation = forms.BooleanField(required=False)

    def clean_topics_interested(self):
        """ split and return include list and exclude list
        """

        include_list = []
        exclude_list = []

        topics = self.cleaned_data['topics_interested']
        for number in topics.split():
            if number.startswith('-'):
                exclude_list.append(number[1:])
            else:
                include_list.append(number)

        return (include_list, exclude_list)

    def clean_knowledge_of_python(self):
        """ if two numbers are given take start and stop.
        else take highest as default.
        """

        range_str = self.cleaned_data['knowledge_of_python'].strip()
        if not range_str:
            return ("","")

        start_stop = range_str.split("-")

        if len(start_stop) == 1:
            if start_stop[0].isdigit():
                return (start_stop[0], "")
            else:
                raise forms.ValidationError("Invalid range for knowledge of Python")

        elif len(start_stop) == 2:
            start, stop = start_stop
            if start.isdigit() and stop.isdigit():
                return (start, stop)
            else:
                 raise forms.ValidationError("Invalid range for knowledge of Python")
        else:
            raise forms.ValidationError("Invalid range for knowledge of Python")
 
    def clean_knowledge_of_sage(self):
        """ if two numbers are given take start and stop.
        else take highest as default.
        """

        range_str = self.cleaned_data['knowledge_of_sage'].strip()
        if not range_str:
            return ("","")

        start_stop = range_str.split("-")

        if len(start_stop) == 1:
            if start_stop[0].isdigit():
                return (start_stop[0], "")
            else:
                raise forms.ValidationError("Invalid range for knowledge of Sage")

        elif len(start_stop) == 2:
            start, stop = start_stop
            if start.isdigit() and stop.isdigit():
                return (start, stop)
            else:
                 raise forms.ValidationError("Invalid range for knowledge of Sage")
        else:
            raise forms.ValidationError("Invalid range for knowledge of Sage")
 
    def clean_likeliness_of_attending(self):
        """ if two numbers are given take start and stop.
        else take highest as default.
        """

        range_str = self.cleaned_data['likeliness_of_attending'].strip()
        if not range_str:
            return ("","")

        start_stop = range_str.split("-")

        if len(start_stop) == 1:
            if start_stop[0].isdigit():
                return (start_stop[0], "")
            else:
                raise forms.ValidationError("Invalid range for Likeliness of attending the workshop")

        elif len(start_stop) == 2:
            start, stop = start_stop
            if start.isdigit() and stop.isdigit():
                return (start, stop)
            else:
                 raise forms.ValidationError("Invalid range for Likeliness of attending the workshop")
        else:
            raise forms.ValidationError("Invalid range for Likeliness of attending the workshop")
                   
class EmailForm(forms.Form):
    """ Take a list of csv seperated email addresses.
    """

    emails = forms.CharField(widget=forms.Textarea, required=False)

    def clean_emails(self):
        emails = self.cleaned_data['emails']

        to_emails = [csv_list.split(',') for csv_list in emails.split()]
        return to_emails

class LoginForm(forms.Form):
    """ login form.
    """

    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

    def clean_username(self):
        username = self.cleaned_data['username']
        try:
            password = self.data['password']
        except KeyError:
            raise forms.ValidationError("Invalid username or password")

        if not authenticate(username=username, password=password):
            raise forms.ValidationError("Invalid username or password")

        return username

def UserSelectForm(users, post_data=None ):

    choices = [ (_.id, _.first_name) for _ in users ]
    class myF(forms.Form):

        selected_users = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=choices, required=False)

        def clean_selected_users(self):
            selected_ids = self.cleaned_data['selected_users']
            return [ Registrant.objects.get(id=_) for _ in selected_ids ]

    return myF(post_data) if post_data else myF()

class ParticipantInfoForm(forms.Form):

    has_laptop_for_sagedays = forms.ChoiceField(choices=(("Yes","Yes"), ("No", "No")))
    sprinted_already = forms.ChoiceField(choices=(("Yes","Yes"), ("No", "No")))
    will_sprint = forms.ChoiceField(choices=SPRINT_CHOICES)
                                         

def SendAccoForm(users, post_data=None):

    choices = [ (_.id, _.first_name) for _ in users ]
    class myF(forms.Form):

	message = forms.CharField(required=True)
        selected_users = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=choices, required=False)

        def clean_selected_users(self):
            selected_ids = self.cleaned_data['selected_users']
            return [ Registrant.objects.get(id=_) for _ in selected_ids ]

	def clean_message(self):
	    message = self.cleaned_data['message']
	    return message.strip()

    return myF(post_data) if post_data else myF()