src/ldt/ldt/user/forms.py
author cavaliet
Fri, 12 Aug 2011 14:44:04 +0200
branchgroup_management
changeset 130 1cc949de2d1f
parent 128 503e365a3af7
child 154 2f83bcf58cc1
permissions -rw-r--r--
Useless code removed. Iri group finally removed from the model. User's templates cleaned. Little css changed for home.

from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.forms.util import ErrorList
from django.utils.translation import gettext as _
from models import ldt


class ldtForm(UserCreationForm):
        
    class Meta:
        model = ldt
        
    def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
                 initial=None, error_class=ErrorList, label_suffix=':',
                 empty_permitted=False, instance=None):
                 
        if instance:
            initial = initial or {}           
        
        super(ldtForm, self).__init__(data, files, auto_id, prefix,
            initial, error_class, label_suffix, empty_permitted, instance)
        
        if instance:
            self.fields['password1'].required = False
            self.fields['password1'].label = _('New password')
            self.fields['password2'].required = False
            self.fields['password2'].label = _('New password confirmation')
        
        self._password_change = True
        
    def clean_username(self):
        if self.instance:
            return self.cleaned_data['username']
        return super(ldtForm, self).clean_username()
    
    def clean_password2(self): 
        if self.instance and self.cleaned_data['password1'] == '' and self.cleaned_data['password2'] == '':
            self._password_change = False
            return u''
        return super(ldtForm, self).clean_password2()
    
   
    def save(self, commit=True):
        Super = self._password_change and ldtForm  or UserCreationForm  
        user = super(Super, self).save(commit=False)
        # if user.pk != None:
            # self.save_m2m()
        
        if commit:
            user.save()
        
        return user

        
class EmailChangeForm(forms.Form):
    email1 = forms.EmailField(label=_("E-mail"), max_length=75)
    email2 = forms.EmailField(label=_("E-mail"), max_length=75)
    
    def __init__(self, user=None, *args, **kwargs):
        self.user = user
        super(EmailChangeForm, self).__init__(*args, **kwargs)
        
    def clean_email2(self):
        email1 = self.cleaned_data.get('email1')
        email2 = self.cleaned_data.get('email2')
        if email1 and email2:
            if email1 != email2:
                raise forms.ValidationError(_("The two emails didn't match."))
        return email2

    
    def save(self):
        self.user.email = self.cleaned_data['email1']
        self.user.save()
        return self.user