django 是否可以向admin/auth/user添加更多字段?

ulydmbyx  于 2022-12-27  发布在  Go
关注(0)|答案(2)|浏览(157)

models.py

class UserProfile(User):
    bio = models.TextField(blank=True, null=True)
    pfp = models.ImageField(verbose_name='Profile Picture', blank=True, null=True, upload_to="images/profile")

forms.py

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField(widget=forms.EmailInput(attrs={"class":"form-control", "placeholder":"example@example.com"}))
    first_name = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control"}))
    last_name = forms.CharField(widget=forms.TextInput(attrs={"class":"form-control"}))
    pfp = forms.ImageField(required=False, widget=forms.FileInput(attrs={"class":"form-control"}))
    bio = forms.CharField(required=False, widget=forms.Textarea(attrs={"class":"form-control", 'rows':5, "placeholder":"Write something about yourself..."}))
    
    class Meta:
        model = UserProfile
        fields = ['first_name', 'last_name', 'username', 'email', "pfp", "bio"]

创建用户时,两个新添加的字段(bio和pfp)没有保存在admin/auth/user中,因此我的问题是,是否可以将这些字段添加到admin用户数据库中?
views.py

class SignUpView(CreateView):
    form_class = UserRegisterForm
    template_name = "registration/signup.html"
    success_url = reverse_lazy("login")
11dmarpk

11dmarpk1#

未保存在admin/auth/user中
事实上,这些在UserProfile模型上是萨费德的。
因此,您可以为此创建一个ModelAdmin

# app_name/admin.py

from django.contrib import admin
from app_name.models import UserProfile

@admin.register(UserProfile)
class AuthorAdmin(admin.ModelAdmin):
    list_display = ('first_name', 'last_name', 'username', 'email', 'pfp', 'bio')

详细信息请参见admin/app_name/userprofile部分。

col17t5w

col17t5w2#

通过继承AbstractUser并添加所需的额外字段来创建自定义用户模型。然后,通过将其分配给AUTH_USER_MODEL来注册该自定义用户模型。
点击此处了解详细实施情况。

相关问题