Ticket #22542: models.py

File models.py, 2.5 KB (added by hoha@…, 11 years ago)

Model file containing a custom user model

Line 
1# -*- coding: utf-8 -*-
2from django.db import models
3from django.conf import settings
4from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser,
5 PermissionsMixin)
6
7
8class BaseModel(models.Model):
9 created_at = models.DateTimeField(auto_now_add=True)
10 created_by = models.ForeignKey(
11 settings.AUTH_USER_MODEL, null=True, blank=True, editable=False,
12 related_name='%(app_label)s_%(class)s_created_related'
13 )
14 updated_at = models.DateTimeField(auto_now=True)
15 updated_by = models.ForeignKey(
16 settings.AUTH_USER_MODEL, null=True,
17 blank=True, editable=False,
18 related_name='%(app_label)s_%(class)s_updated_related'
19 )
20
21 class Meta:
22 abstract = True
23
24
25class AccountManager(BaseUserManager):
26 def _create_user(self, username, email, password, is_staff, is_superuser,
27 **kwargs):
28 if not username:
29 raise ValueError('Accounts must have a username.')
30 if not email:
31 raise ValueError('Accounts must have an e-mail address.')
32
33 email = self.normalize_email(email)
34 user = self.model(username=username, email=email, is_staff=is_staff,
35 is_superuser=is_superuser, **kwargs)
36
37 user.set_password(password)
38 user.save(using=self._db)
39
40 return user
41
42 def create_user(self, username, email, password=None, **kwargs):
43 return self._create_user(username, email, password, is_staff=False,
44 is_superuser=False, **kwargs)
45
46 def create_superuser(self, username, email, password, **kwargs):
47 return self._create_user(username, email, password, is_staff=True,
48 is_superuser=True, **kwargs)
49
50
51class Account(AbstractBaseUser, PermissionsMixin, BaseModel):
52 username = models.CharField(max_length=100, unique=True)
53 email = models.EmailField(max_length=254, unique=True)
54 first_name = models.CharField(max_length=255, blank=True)
55 last_name = models.CharField(max_length=255, blank=True)
56 is_staff = models.BooleanField(default=False)
57 is_active = models.BooleanField(default=True)
58
59 objects = AccountManager()
60
61 USERNAME_FIELD = 'username'
62 REQUIRED_FIELDS = ['email']
63
64 def get_full_name(self):
65 return '{0} {1}'.format(self.first_name, self.last_name)
66
67 def get_short_name(self):
68 return self.first_name
69
70 def __str__(self):
71 return self.username
72
73 def email_user(self, subject, message, from_email=None, **kwargs):
74 raise NotImplementedError()
75
Back to Top