我正在学习Django并需要一些帮助。
我需要在我的用户模型中包含一个额外的布尔字段(我相信的数据库中的auth_user表),并在管理用户时显示在管理界面中,例如此图像中的人员状态字段...
127:0.0.1:8000 / admin / user :
和...
127.0.0.1:8000/admin/auth/user/2/change / :
我不确定如何处理这个问题。我理解我必须扩展AbstractUser模型然后手动将字段添加到数据库中,但是如何为管理员更新视图,表单和模板的新字段接口?我是否必须为所有这些重写django管理员源代码,还是有更简单的方法?
答案 0 :(得分:4)
最好的方法是使用User OneToOneField创建新模型。 e.g
{{1}}
您可以在用户模型或UserProfile模型中使用django admin,并可以相应地显示Admin中的字段
答案 1 :(得分:1)
答案 2 :(得分:1)
这是我的方法:
注意:创建新项目时应这样做。
将字段添加到用户模型:-
models.py:
from django.db import models
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
gender = models.BooleanField(default=True) # True for male and False for female
# you can add more fields here.
覆盖默认的用户模型:-
settings.py:
# the example_app is an app in which models.py is defined
AUTH_USER_MODEL = 'example_app.User'
在管理页面上显示模型:-
admin.py:
from django.contrib import admin
from .models import User
admin.site.register(User)
答案 3 :(得分:0)
#managers.py Create new file.
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import ugettext_lazy as _
class CustomUserManager(BaseUserManager):
def create_user(self, email, password, **extra_fields):
if not email:
raise ValueError(_('The Email must be set'))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
extra_fields.setdefault('is_active', True)
if extra_fields.get('is_staff') is not True:
raise ValueError(_('Superuser must have is_staff=True.'))
if extra_fields.get('is_superuser') is not True:
raise ValueError(_('Superuser must have is_superuser=True.'))
return self.create_user(email, password, **extra_fields)
#models.py Create your models here.
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.utils.translation import gettext_lazy as _
from .managers import CustomUserManager
class User(AbstractBaseUser,PermissionsMixin):
first_name =models.CharField(max_length=250)
email = models.EmailField(_('email address'), unique=True)
mobile =models.CharField(max_length=10)
status = models.BooleanField(default=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
object =CustomUserManager()
# add more your fields
#admin.py
from django.contrib import admin
from .models import User
@admin.register(User)
class UserAdmin(admin.ModelAdmin):
list_display = ('email','mobile','password')
#setting.py
AUTH_USER_MODEL = 'users.User'
# run command
python manage.py makemigrations
python manage.py migrate