06.Django中使用者的兩種擴充套件方式(Profile和AbstractUser)

Thinkgamer_gyt發表於2016-01-11
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

後臺登陸即可

相關文章