from django.contrib.auth.models import User
from django import forms
from django.utils.translation import ugettext as _

class AccountForm(forms.ModelForm):
    email = forms.EmailField(required=True)

    class Meta:
        model = User
        fields = ['username', 'email']

    def __init__(self, *args, **kwargs):
        # Update initial data
        # We expect username with "nickname" key
        # This key (and others) are generated by
        # openid Sreg/AX extensions processor
        initial = kwargs.setdefault('initial', {})
        initial['username'] = initial.get('nickname', '')
        super(AccountForm, self).__init__(*args, **kwargs)

    def clean_username(self):
        username = self.cleaned_data['username']
        try:
            User.objects.get(username=username)
        except User.DoesNotExist:
            return username
        else:
            raise forms.ValidationError(_('This username is already registered'))

    def clean_email(self):
        email = self.cleaned_data['email']
        try:
            User.objects.get(email=email)
        except User.DoesNotExist:
            return email
        else:
            raise forms.ValidationError(_('This email is already registered'))
