Django中擴展User模型

官方其實是有資料的,不過在這裏還是寫的淺顯點。

官方地址https://docs.djangoproject.com/en/dev/topics/auth/customizing/


在實際開發過程中,django提供的user字段肯定是不夠用的,比如用戶積分啊,描述啊,頭像呀。。。這時候就需要擴展auth.User模型。


擴展User有2種方式。1種是建1個新的模型,然後User做爲外鍵導入。


以下用pycharm來演示


建立工程


建立好以後進入命令行模式


執行命令(因爲我用的是virtualenv虛擬環境,因此有前面的一段進入虛擬環境的過程,否則直接執行紅框內的命令就ok)


設置數據庫


接下來演示第一種模式

擴展User

配置好以後,設置模型


代碼:

[python] view plaincopy

  1. #coding: utf-8  

  2. from django.db import models  

  3. from django.contrib.auth.models import User  

  4. from django.db.models.signals import post_save  

  5.   

  6. class UserProfile(models.Model):  

  7.     user = models.OneToOneField(User)  

  8.     description = models.TextField(max_length=51200)  

  9.     scope = models.IntegerField(default=100)  

  10.   

  11. def create_user_profile(sender, instance, created, **kwargs):  

  12.     if created:  

  13.        profile, created = UserProfile.objects.get_or_create(user=instance)  

  14.   

  15. post_save.connect(create_user_profile, sender=User)  


修改view代碼爲


代碼:

[python] view plaincopy

  1. #coding: utf-8  

  2. from django.http import HttpRequest, HttpResponse  

  3. from django.contrib.auth.models import User  

  4. from .models import UserProfile  

  5.   

  6. def userDemo(request):  

  7.     desc = User.objects.all()[0].get_profile().description  

  8.     return HttpResponse(desc)  


新建urls文件,並填充代碼


代碼:

[python] view plaincopy

  1. #coding: utf-8  

  2. __author__ = 'watsy'  

  3. from django.conf.urls import patterns, include, url  

  4. from .views import userDemo  

  5.   

  6. urlpatterns = patterns('',  

  7.     url(r'^profile/$', userDemo),  

  8. )  

添加admin.py文件,並添加代碼


代碼:

[python] view plaincopy

  1. #coding: utf-8  

  2. __author__ = 'watsy'  

  3.   

  4. from django.contrib import admin  

  5. from .models import UserProfile  

  6.   

  7. class UserProfileAdmin(admin.ModelAdmin):  

  8.     fields = ('user','description',)  

  9.   

  10. admin.site.register(UserProfile, UserProfileAdmin)  



接下來修改入口url代碼:


插入代碼:

[python] view plaincopy

  1. url('^user/', include('MyUser.urls')),  

接下來修改配置文件。



接下來執行模型導入數據庫



輸入admin的帳號密碼


接下來在瀏覽器中輸入

http://127.0.0.1:8000/admin/

輸入帳號密碼 demo admin



瀏覽器中輸入

http://127.0.0.1:8000/user/profile/


第二種方案

修改替代User

http://www.roguelynn.com/words/django-custom-user-models/

官方文檔地址https://docs.djangoproject.com/en/dev/topics/auth/customizing/#substituting-a-custom-user-model

雖然是全英文的,不過代碼寫的很清晰,這裏就不寫拉。偷懶一下。有興趣的留言,下次在詳細寫。

第三種方案

從User派生

這種方案是測試過使用效果不錯的。

首先來設定模型類。


代碼:

[python] view plaincopy

  1. from django.db import models  

  2. from django.contrib.auth.models import User, UserManager  

  3. from .signals import *  

  4.   

  5. class CustomUser(User):  

  6.     description = models.TextField(max_length=256, default="",blank=True)  

  7.     headImage = models.ImageField(upload_to='/media/p_w_picpath/users/',null=True, blank=True)  

  8.     scope = models.IntegerField(default=100)  

  9.   

  10.     objects = UserManager()  



接下來利用信號方法,當用戶創建User時候,填充CustomUser模型實例。


代碼:

[python] view plaincopy

  1. from django.db.models.signals import post_save  

  2. from django.contrib.auth.models import User  

  3. def create_user_detail(sender, instance, signal, *args, **kwargs):  

  4.     print sender, instance, signal, args, kwargs  

  5.     from .models import CustomUser  

  6.     if kwargs['created']:  

  7.         u = CustomUser()  

  8.         u.__dict__.update(instance.__dict__)  

  9.         u.save()  

  10.   

  11. post_save.connect(create_user_detail, sender=User)  


接下來註冊到admin中


修改settings.py中配置。

添加

[python] view plaincopy

  1. CUSTOM_USER_MODEL = 'UserProfile.CustomUser'  


通過restframework來測試一下。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章