Django自带的User模型没有头像和电话这两项属性,因此需要通过扩展User达到我们想要的效果,根据官方的文档,扩展新字段到User只需要用one-to-one模型即可。
一、创建一个APP
python manage.py startapp CustomUser
二、在models里面创建用户模型,使用one-to-one关联User
from __future__ import unicode_literals 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(max_length=20, null=True, blank=True) avatar = models.ImageField(upload_to='photo', null=True, blank=True)
三、增加admin配置,admin后台可以填写这两个新字段:
from django.contrib import admin from django.contrib.auth.admin import UserAdmin 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 = 'myuser' # Define a new User admin class UserAdmin(UserAdmin): inlines = (EmployeeInline, ) # Re-register UserAdmin admin.site.unregister(User) admin.site.register(User, UserAdmin)
admin后台效果:
四、修改settings User指向:
AUTH_PROFILE_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>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。