06.Django中用户的两种扩展方式(Profile和AbstractUser)

1:profile扩展
正常建立一个项目:

python-admin.py startproject myweb

建立子项目
manage.py startapp user

子项目配置如下:
models.py
from django.db import models
from django.contrib.auth.models import User #导入admin的User
from django.db.models.signals import post_save

# Create your models here.

class UserProfile(models.Model):
user = models.OneToOneField(User)
description = models.TextField(max_length=51200)
scope = models.IntegerField(default=100)
admin.py
#coding:utf-8
from django.contrib import admin
from django.contrib.auth.models import User
from login.models import UserProfile

# Register your models here.
class ProfileInline(admin.StackedInline): #将UserProfile加入到Admin的user表中
model = UserProfile
verbose_name = 'profile'

class UserProfileAdmin(admin.ModelAdmin):
inlines = (ProfileInline,)

admin.site.unregister(User) #去掉在admin中的注册
admin.site.register(User, UserProfileAdmin) #用userProfileAdmin注册user
views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.contrib.auth.models import User
from login.models import UserProfile
# Create your views here.

def userDemo(request):
desc = User.objects.all()[0]
return HttpResponse(desc)

配置URL:
myweb目录下的url:
from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^login/', include('login.urls'))
]


赋值一份urls.py 到user的目录下,修改urlpatterns 如下:

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
url(r'^login/$', 'login.views.userDemo')
]

数据库的同步:
makemigrations
migrate
syncdb

后台登陆查看


二:继承AbstractUser


新建一个项目如Profile所示
myweb修改添加如下语句:
AUTH_USER_MODEL = 'login.User'
login中:
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser

# Create your models here.

class User(AbstractUser): #继承AbstractUser
desc = models.TextField()
admin.py
#coding:utf-8
from django.contrib import admin

# Register your models here.
from login.models import User
admin.site.register(User)
其余的URL配置  ,views.py配置和settings.py的部分配置同profile的配置方式

数据库的同步:
makemigrations
migrate
syncdb

后台登陆即可

你可能感兴趣的:(#,Django系列,Django从零开始到项目优化)