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

时间:2018-08-21 19:35:36

标签: python django

我刚开始使用Django,并且刚刚修改了我的项目,因此我不使用基本用户,而是使用我在models.py文件夹中定义的AbstractUser模型

#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 enter image description here

我的问题是,点击用户后,如何创建一个字段来编辑此CustomUser属性?,例如,像这样的enter image description here我d欢迎任何帮助,因为我不太擅长阅读文档。请问您是否需要在问题中添加更多代码,我之前从未问过Django问题

1 个答案:

答案 0 :(得分:1)

再看一遍后,我发现可以在我的fieldsets代码内部使用的CustomUserAdmin选项(link1link2link3)。在我的CustomUserAdmin班上,我有:

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

    fieldsets = UserAdmin.fieldsets + (
            ('Extra Fields', {'fields': ('favourite_colour',)}),
    )