您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。