DjangoWeb开发--增加用户字段

DjangoWeb开发--增加用户字段

在django默认的用户表中增加字段比如用户简介,QQ号。

1.使用外键扩展
  • models.py
from django.contrib.auth.models import User     
class UserProfile(models.Model):    
    user = models.OneToOneField(User)   
    desc = models.TextField(blank=True, null=True)
  • admin.py
from django.contrib.auth.models import User     
from blog.models import UserProfile     
class ProfileInline(admin.StackedInline):   
    model = UserProfile     
    verbose_name = 'profile'    
class UserAdmin(admin.ModelAdmin):      
    inlines = (ProfileInline,)      
admin.site.unregister(User)     
admin.site.register(User, UserAdmin)    
  • views.py
from django.contrib.auth.models import User     
def user(request):      
    users = User.objects.all()      
    for user in users:      
        print user.userprofile.desc     
    return HttpResponse(users)      
2.继承AbstractUser(这种方法更好)
  • models.py
from django.contrib.auth.models import AbstractUser     
class User(AbstractUser):   
    desc = models.TextFiled()   
  • settings.py
AUTH_USER_MODEL = 'blog.User'   
  • admin.py
from blog.models import User
admin.site.register(User)

你可能感兴趣的:(DjangoWeb开发--增加用户字段)