我刚开始使用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)
我的问题是,点击用户后,如何创建一个字段来编辑此CustomUser
属性?,例如,像这样的我d欢迎任何帮助,因为我不太擅长阅读文档。请问您是否需要在问题中添加更多代码,我之前从未问过Django问题
答案 0 :(得分:1)
再看一遍后,我发现可以在我的fieldsets
代码内部使用的CustomUserAdmin
选项(link1,link2,link3)。在我的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',)}),
)