Django自带的User模型没有头像和电话这两项属性,因此需要通过扩展User达到我们想要的效果,根据官方的文档,扩展新字段到User只需要用one-to-one模型即可。
一、创建一个APP
1
|
python manage.py startapp CustomUser
|
二、在models里面创建用户模型,使用one-to-one关联User
1
2
3
4
5
6
7
8
9
10
11
12
|
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后台可以填写这两个新字段:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
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指向:
1
|
AUTH_PROFILE_MODULE
=
'CustomUser.MyUser'
|
五、生成数据库:
1
2
|
python manage.py makemigrations CustomUser
python manage.py migrations
|
六、上传头像需要media配置,故settings需增加配置:
1
2
|
MEDIA_URL
=
'/media/'
MEDIA_ROOT
=
os.path.join(BASE_DIR,
'media'
)
|
在manage.py同一层新建media目录
七、配置urls.py:
1
2
3
4
|
from
django.conf
import
settings
from
django.conf.urls.static
import
static
urlpatterns
+
=
static(settings.MEDIA_URL, document_root
=
settings.MEDIA_ROOT)
|
八、template上使用头像:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<
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
>
本文转自运维笔记博客51CTO博客,原文链接http://blog.51cto.com/lihuipeng/1836996如需转载请自行联系原作者 lihuipeng
|