1. 程式人生 > >django重寫使用者模型

django重寫使用者模型

重寫一個UserProfile繼承自帶的AbstractUser

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from datetime import datetime

from django.db import models
from django.contrib.auth.models import AbstractUser


# Create your models here.


class UserProfile(AbstractUser):
    nick_name = models.CharField(max_length=50, verbose_name=u"暱稱", default='')
    birthday = models.DateField(verbose_name=u"生日", null=True, blank=True)
    gender = models.CharField(max_length=5, verbose_name=u"性別", choices=(("male", u"男"), ("female", u"女")), default="female")
    address = models.CharField(max_length=100, default=u"")
    mobile = models.CharField(max_length=11, null=True,blank=True)
    image = models.ImageField(upload_to="image/%Y/%m/%d", default=u"image/default.png", max_length=100)

    class Meta:
        verbose_name = u"使用者資訊"
        verbose_name_plural = verbose_name

    def __unicode__(self):
        return self.username

在settings內增加定義

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users',
]
AUTH_USER_MODEL = "users.UserProfile"

其中AUTH_USER_MODEL = "users.UserProfile"一定要在第一次遷移資料庫前做,要不會出現錯誤,出現錯誤要刪掉以前資料庫
具體參考https://www.jianshu.com/p/b993f4feff83