django-userena扩展了django原生的用户系统,提供了注册、登录、修改密码、邮件验证等一系列常用功能。直接使用pip安装即可:pip install django-userena

会自动安装其所需的依赖包,不过个人建议为了更好的定制模板或相关功能,把这个包放到项目目录下当作一个app更方便一些。安装完成后修改settings.py,首先来创建一个app用于扩展用户系统
python manage.py startapp accounts
然后修改Models.py来扩展原生用户字段,我这里以添加用户等级为例:

1
2
3
4
5
6
7
8
9
10
11
# coding=utf-8
from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import ugettext as _
from userena.models import UserenaBaseProfile
class CustomerProfile(UserenaBaseProfile):
user = models.OneToOneField(User,
unique=True,
verbose_name=_('user'),
related_name='customer_profile')
level = models.IntegerField(_(u"用户等级"), default=0)

接下来修改settings.py,首先把

1
2
3
4
5
"django.contrib.sites",
"accounts",
'userena',
'guardian',
'easy_thumbnails'

添加到INSTALLED_APPS中,然后把'django.contrib.sites.middleware.CurrentSiteMiddleware',
添加到MIDDLEWARE_CLASSES中,在django1.7.7中如果不添加和site有关的东西时,userena注册用户会抛出”Site matching query does not exist“异常。最后添加下面的配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
AUTHENTICATION_BACKENDS = (
'userena.backends.UserenaAuthenticationBackend',
'guardian.backends.ObjectPermissionBackend',
'django.contrib.auth.backends.ModelBackend',
)
EMAIL_HOST = 'xxxx'
EMAIL_HOST_USER = 'xxxx@xxxx'
EMAIL_HOST_PASSWORD = 'xxxx'
EMAIL_PORT = 25
DEFAULT_FROM_EMAIL = 'xxxx@xxxx'
ANONYMOUS_USER_ID = -1
AUTH_PROFILE_MODULE = 'accounts.CustomerProfile'
USERENA_SIGNIN_REDIRECT_URL = '/accounts/%(username)s/'
LOGIN_URL = '/accounts/signin/'
LOGOUT_URL = '/accounts/signout/'

xxxx根据实际情况修改,和发送验证邮件有关。这些都添加完毕后,执行
./manage.py migrate
创建数据库,接下来执行
./manage.py check_permissions
否则报错”Permission matching query does not exist“。最后记得添加url

1
url(r'^accounts/', include('userena.urls')),

都完成后,运行程序,访问http://127.0.0.1:8000/accounts/signup/就可以看见注册页面了。

所有html文件以及email模板都在userena/templates/userena路径下,进行相应定制即可。