在django-allauth教程(1)我们讲解了django-allauth的安装及基本使用(如用户的注册,登录,邮箱验证和密码重置)。我们也提到了allauth并没有提供展示和修改用户资料的功能,也没有对用户资料进行扩展,今天我们就来补上这块。在本文里,我们将会开发两个功能页面,一个在用户登录后跳转到个人信息页面(/accounts/profile/),一个允许登录用户编辑个人资料/accounts/profile/update/)。
我们的教程会一共分4部分,欢迎关注我们微信公众号。本文是第2部分。
-
安装与基本使用(注册,登录, 邮箱验证,密码重置) - 已完结
-
用户资料扩展及修改
-
实现第三方auth登录
-
美化登录与注册表单
第一步 创建应用及配置
由于django-allauth已经占用了account这个app名,所以我们需要先创建一个叫myaccount的app,并将其加入到settings.py配置文件INSTALLED_APP里去,同时把urls也加入到项目的urls里去,如下图所示。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myaccount',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.weibo',
]
项目的urls.py文件如下所示:
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('allauth.urls')),
path('accounts/', include('myaccount.urls')),
]
因为我们希望用户在登录或注册后自动跳转到/accounts/profile/, 我们可以加入以下代码。
LOGIN_REDIRECT_URL = '/accounts/profile/'
第二步 编写模型
由于Django自带的User模型字段邮箱,所以我们需要对其扩展,最便捷的方式就是创建UserProfile的模型,如下所示。我们添加了org和telephone两个字段。
# myaccount/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
org = models.CharField(
'Organization', m