Django自带的User模型没有头像和电话这两项属性,因此需要通过扩展User达到我们想要的效果,根据官方的文档,扩展新字段到User只需要用one-to-one模型即可。
一、创建一个APP
python manage.py startapp CustomUser
二、在models里面创建用户模型,使用one-to-one关联User
from __future__ import unicode_literalsfrom django.db import models# Create your models here.from django.contrib.auth.models import Userclass 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 adminfrom django.contrib.auth.admin import UserAdminfrom django.contrib.auth.models import Userfrom CustomUser.models import MyUser# Define an inline admin descriptor for Employee model# which acts a bit like a singletonclass EmployeeInline(admin.StackedInline): model = MyUser can_delete = False verbose_name_plural = 'myuser'# Define a new User adminclass UserAdmin(UserAdmin): inlines = (EmployeeInline, )# Re-register UserAdminadmin.site.unregister(User)admin.site.register(User, UserAdmin)
admin后台效果:
四、修改settings User指向:
AUTH_PROFILE_MODULE = 'CustomUser.MyUser'
五、生成数据库:
python manage.py makemigrations CustomUserpython 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 settingsfrom django.conf.urls.static import staticurlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
八、template上使用头像: