Django使用Profile擴充套件User模組方式
阿新 • • 發佈:2020-05-15
首先建立Profile應用
python manage.py startapp profiles
profiles/models.py
# -*- coding: utf-8 -*- from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User) nickname = models.CharField(max_length=16,default='',blank=True) sex = models.IntegerField(default=0) phone = models.CharField(max_length=16,blank=True) def __str__(self): return self.nickname def __unicode__(self): return self.nickname def create_user_profile(sender,instance,created,**kwargs): if created: profile = UserProfile() profile.user = instance profile.save() post_save.connect(create_user_profile,sender=User)
profiles/admin.py
# -*- coding: utf-8 -*- from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin from .models import UserProfile class ProfileInline(admin.StackedInline): model = UserProfile max_num = 1 can_delete = False class UserProfileAdmin(UserAdmin): inlines = [ProfileInline,] admin.site.unregister(User) admin.site.register(User,UserProfileAdmin)
settings.py
新增
AUTH_PROFILE_MODULE = 'profiles.UserProfile'
測試
$ python manage.py syncdb $ python manage.py shell >>> from django.contrib.auth.models import User >>> user = User() >>> user.username='testuser' >>> user.save() >>> User.objects.all()[0].userprofile
補充知識:django中登入到accounts/profile/的解決方案
在project的setting里加一句話就Okay!
LOGIN_REDIRECT_URL = '/index'
以上這篇Django使用Profile擴充套件User模組方式就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。