Commits

Petar Radosevic committed a88e320

Modeling admin for account

  • Participants
  • Parent commits aaad08c

Comments (0)

Files changed (6)

-James Bennett: b-list.org
+James Bennett: http://b-list.org
 Grigoriy Petukhov: http://web-brains.com

File requirements.txt

+# Dateutil
+python-dateutil
       url='http://github.com/wunki/django-userenity',
       download_url='http://github.com/wunki/django-userenity/downloads',
       packages=['accounts'],
+      requires=[
+        'django (>1.1.0)',
+        'python-dateutil (>1.5)',
+      ],
       classifiers=['Development Status :: 4 - Beta',
                    'Environment :: Web Environment',
                    'Framework :: Django',

File userenity/admin.py

+from django.contrib import admin
+
+from userenity.models import Account
+from userenity.forms import AccountForm
+
+class AccountAdmin(admin.ModelAdmin):
+    form = AccountForm
+
+admin.site.register(Account, AccountAdmin)

File userenity/forms.py

+from django import forms
+from django.utils.translation import ugettext_lazy as _
+from django.contrib.auth.models import User
+
+from userenity.models import Account
+
+class AccountForm(forms.ModelForm):
+    """
+    A form that implements all the fields for a user.
+
+    We don't want to edit a seperate user and account form.
+
+    """
+    def __init__(self, *args, **kwargs):
+        super(AccountForm, self).__init__(*args, **kwargs)
+        try:
+            self.current_user = self.instance.user
+        except User.DoesNotExist:
+            self.current_user = None
+        else:
+            self.fields['username'].initial = self.current_user.username
+            self.fields['email'].initial = self.current_user.email
+            self.fields['first_name'].initial = self.current_user.first_name
+            self.fields['last_name'].initial = self.current_user.last_name
+
+    username = forms.RegexField(label=_('Username'), max_length=30, regex=r'^[\w.@+-]+$',
+        help_text = _('Required. 30 characters or fewer. Letters, digits and @.+-_ only.'),
+        error_messages = {'invalid': _('This value may contain only letters, numbers and @/./+/-/_ characters.')})
+    email = forms.EmailField(label=_('Email'))
+    password_1 = forms.CharField(label=_('Password'), widget=forms.PasswordInput, required=False)
+    password_2 = forms.CharField(label=_('Password again'), widget=forms.PasswordInput, required=False)
+    first_name = forms.CharField(label=_('First name'), max_length=30, required=False)
+    last_name = forms.CharField(label=_('Last name'), max_length=30, required=False)
+
+    class Meta:
+        model = Account
+        fields = ['username','email', 'password_1', 'password_2', 'first_name', 'last_name', 'mugshot', 'gender', 'birth_date', 'website']
+
+    def clean_username(self):
+        username = self.cleaned_data['username']
+        try:
+            User.objects.get(username=username)
+        except User.DoesNotExist:
+            return username
+        raise forms.ValidationError(_('A user with that username already exists.'))
+
+    def clean_password_1(self):
+        # Check passwords for new user
+        if self.current_user:
+            if 'password_1' in self.cleaned_data and 'password_2' in self.cleaned_data:
+                if self.cleaned_data['password1'] != self.cleaned_data['password2']:
+                    raise forms.ValidationError(_('Passwords are not equal'))
+            else:
+                raise forms.ValidationError(_('Passwords are required for a new user'))
+        # Existing user
+        else:
+            if 'password_1' in self.cleaned_data and 'password_2' in self.cleaned_data:
+                if self.cleaned_data['password1'] != self.cleaned_data['password2']:
+                    raise forms.ValidationError(_('Passwords are not equal'))
+        return self.cleaned_data['password_1']
+
+    def save(self, *args, **kwargs):
+        """
+        Update the account and user.
+
+        """
+        if self.current_user: # Update the current user
+            u.email = self.cleaned_data['email']
+            u.save()
+
+        else: # Create a new user
+            user = User.objects.create_user(self.cleaned_data['username'],
+                                            self.cleaned_data['email'],
+                                            self.cleaned_data['password_1'])
+            self.user_id = user.id
+
+        account = super(AccountForm, self).save(*args,**kwargs)
+        return account

File userenity/models.py

 from django.db import models
+from django.utils.translation import ugettext_lazy as _
+from django.contrib.auth.models import User
 
-# Create your models here.
+import datetime, dateutil
+
+class Account(models.Model):
+    """
+    A user account which stores all the nescessary information to have a full
+    functional user implementation on your Django website.
+
+    """
+    GENDER_CHOICES = (
+        (1, _('Male')),
+        (2, _('Female')),
+    )
+    user = models.ForeignKey(User, unique=True, verbose_name=_('user'))
+    mugshot = models.FileField(_('mugshot'), upload_to='mugshots', blank=True)
+    gender = models.PositiveSmallIntegerField(_('gender'), choices=GENDER_CHOICES, blank=True, null=True)
+    birth_date = models.DateField(_('birth date'), blank=True, null=True)
+    website = models.URLField(_('website'), blank=True, verify_exists=True)
+
+    def __unicode__(self):
+        return u'%s' % self.user
+
+    @models.permalink
+    def get_absolute_url(self):
+        pass
+
+    @property
+    def age(self):
+        TODAY = datetime.date.today()
+        return u'%s' % dateutil.relativedelta(TODAY, self.birth_date).years