姜戈.如何在 User 模型中添加额外的字段并将其显示在管理界面中 [英] Django. How to add an extra field in User model and have it displayed in the admin interface

查看:28
本文介绍了姜戈.如何在 User 模型中添加额外的字段并将其显示在管理界面中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Django,需要一些帮助.

我需要在我的用户模型中包含一个额外的布尔字段(我相信数据库中的 auth_user 表),并在管理用户时将其显示在管理界面中,例如此图像中的员工状态字段...

127:0.0.1:8000/admin/user :

还有……

127.0.0.1:8000/admin/auth/user/2/change/:

我不确定如何解决这个问题.我知道我必须扩展 AbstractUser 模型,然后可能手动将该字段添加到数据库中,但是如何更新管理界面的视图、表单和模板的新字段?我是否必须为所有这些重写 django 管理源代码,还是有更简单的方法?

解决方案

最好的方法是使用 User OneToOneField 创建新模型.例如

class UserProfile(models.Model):用户 = 模型.OneToOneField(用户)phone = models.CharField(max_length=256, blank=True, null=True)性别 = 模型.CharField(max_length=1, 选择=(('m', _('Male')), ('f', _('Female'))),空白=真,空=真)

您可以在 User Model 或 UserProfile Model 中使用 django admin,并可以相应地在 Admin 中显示字段

I'm learning Django and need some help.

I need to include an extra boolean field in my User Model (auth_user table in the db I believe) and have it be displayed in the admin interface when managing users, like the staff status field in this image...

127:0.0.1:8000/admin/user :

and...

127.0.0.1:8000/admin/auth/user/2/change/ :

I'm unsure on how to approach this. I understand I'll have to extend the AbstractUser model and then perhaps manually add the field into the db, but then how do I update the new field for the view, form and templates for the admin interface? Will I have to rewrite the django admin source code for all of these or is there an simpler way?

解决方案

The best way is to create new Model with User OneToOneField. e.g

class UserProfile(models.Model):
   user = models.OneToOneField(User)
   phone = models.CharField(max_length=256, blank=True, null=True)
   gender = models.CharField(
        max_length=1, choices=(('m', _('Male')), ('f', _('Female'))),
        blank=True, null=True)

You can play with django admin either in User Model or UserProfile Model and can display the fields in Admin accordingly

这篇关于姜戈.如何在 User 模型中添加额外的字段并将其显示在管理界面中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆