问题描述
我正在学习Django,需要一些帮助。
I'm learning Django and need some help.
我需要在我的用户模型中添加一个布尔值字段(我相信数据库中的auth_user表),并在管理用户时将其显示在管理界面中,例如
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 :
和...
127.0.0.1:8000/admin/auth/user/2/change / :
我不确定该如何处理。我知道我必须扩展AbstractUser模型,然后手动将字段添加到数据库中,但是该如何为管理界面的视图,表单和模板更新新字段?我是否需要重写所有这些的django admin源代码,还是有更简单的方法?
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?
推荐答案
最好的方法是使用用户OneToOneField创建新模型。例如
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)
您可以在用户模型或UserProfile模型中与django admin一起玩,并可以在Admin中相应地显示字段
You can play with django admin either in User Model or UserProfile Model and can display the fields in Admin accordingly
这篇关于Django的。如何在用户模型中添加额外字段并将其显示在管理界面中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!