Django自带的User模型没有头像和电话这两项属性,因此需要通过扩展User达到我们想要的效果,根据官方的文档,扩展新字段到User只需要用one-to-one
(一对一)模型即可。
一、创建一个APP
python manage.py startapp CustomUser
二、在models里面创建用户模型,使用one-to-one关联User
from django.db import models
# Create your models here.
from django.contrib.auth.models import User
class MyUser(models.Model):
user = models.OneToOneField(User)
phone = models.CharField(u'手机号',max_length=13, null=True, blank=True)
avatar = models.ImageField(u'管理员头像',upload_to='images', null=True, blank=True)
class Meta:
verbose_name = u'头像管理'
三、增加admin配置,admin后台可以填写这两个新字段:
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from CustomUser.models import MyUser
# Define an inline admin descriptor for Employee model
# which acts a bit like a singleton
class EmployeeInline(admin.StackedInline):
model = MyUser
can_delete = False
verbose_name_plural = u'管理中心'
# Define a new User admin
class UserAdmin(BaseUserAdmin):
inlines = (EmployeeInline, )
# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)
admin后台效果:
四、修改settings User指向:
AUTH_USER_MODULE = 'CustomUser.MyUser'
五、生成数据库:
python manage.py makemigrations CustomUser
python manage.py migrations
六、上传头像需要media配置,故settings需增加配置:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
在manage.py同一层新建media目录
七、配置urls.py:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
八、template上使用头像:
<ul class="nav navbar-nav navbar-right">
<li class="dropdown navbar-user">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown">
<img src="{{ request.user.myuser.avatar.url }}" alt="" />
<span class="hidden-xs">{{ request.user.username }}</span> <b class="caret"></b>
</a>
<ul class="dropdown-menu animated fadeInLeft">
<li class="arrow"></li>
<li><a href="javascript:;">编辑资料</a></li>
<li><a href="javascript:;">重置密码</a></li>
<li class="divider"></li>
<li><a href="{{ url('logout') }}">退出系统</a></li>
</ul>
</li>
</ul>