如何在Django Admin中添加一个额外的字段?

6 人关注

我刚刚开始使用Django,我刚刚修改了我的项目,不再使用基本用户,而是使用AbstractUser模型,正如我的models.py文件夹中定义的那样

#accounts/models.py
from django.contrib.auth.models import AbstractUser
from django.db import models
class CustomUser(AbstractUser):
    # add additional fields in here
    favourite_colour = models.CharField("Favourite Colour", max_length=100)
    def __str__(self):
        return self.email

我还创建了创建表格,与我的注册系统配合得很好。

#accounts/forms.py
from django.contrib.auth.forms import UserCreationForm, UserChangeForm
from django.contrib.auth.models import User
from django import forms
from .models import CustomUser
class CustomUserCreationForm(UserCreationForm):
    class Meta(UserCreationForm.Meta):
        model = CustomUser
        fields = ('username', 'email', 'favourite_colour')
        help_texts = {
                    'username': 'Make something unique',
                    'email': None,
class CustomUserChangeForm(UserChangeForm):
    class Meta:
        model = CustomUser
        fields = ('username', 'email', 'favourite_colour')

现在我正试图编辑管理页面,以便我能够改变一个用户的favourite_colour属性。到目前为止,我的admin.py文件中是这样的

#accounts/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser
class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['username', 'email', 'favourite_colour']
admin.site.register(CustomUser, CustomUserAdmin)

这显示了每个用户的favourite_colour

My question is, 如何使一个字段在你点击一个用户后编辑这个CustomUser的属性?,比如说像这样enter image description here我欢迎任何帮助,因为我不太擅长阅读文档。如果你需要更多的代码添加到问题中,请提问,我以前从来没有问过Django问题。

python
django
Crawley
Crawley
发布于 2018-08-22
1 个回答
Crawley
Crawley
发布于 2018-08-22
已采纳
0 人赞同

经过进一步查找,我发现了一个 fieldsets 选项( link1 , link2 , link3 ),可以在我的 CustomUserAdmin 代码中使用。在我的 CustomUserAdmin 类中,我现在有。

class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['username', 'email', 'favourite_colour']