django管理员中重新定义的工作表单不正确

我已经创建了自定义模型配置文件并将其链接到用户模型,该模型工作正常 . 但是,现在我想在Django admin中创建自定义UserCreateForm . 我重新定义了它并添加了必要的字段,但之后仍然显示了来自配置文件模型的所有字段,例如:phone,home_address . 我需要在UserCreateForm中显示为“first_name”,“last_name”,“username”,“password1”,“password2”的字段 . 我做错了什么?

from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm
from .models import Profile

class NewUserCreateForm(UserCreationForm):

   class Meta:
       fields = ('username', 'first_name', 'last_name',)

class ProfileInline(admin.TabularInline):
    model = Profile

class UserAdmin(UserAdmin):

   add_form = NewUserCreateForm

   add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('first_name', 'last_name', 'username','password1', 'password2', ),
       }),
       )
   inlines = [ProfileInline]

admin.site.unregister(User)
admin.site.register(User, UserAdmin)

回答(1)

2 years ago

首先你的 models.py 文件将是:

from django.db import models

from django.contrib.auth.models import User

# Create your models here.

class Profile(models.Model):
    user_id = models.OneToOneField(User, on_delete=models.CASCADE) 
    phone = models.CharField(max_length=100)
    address = models.CharField(max_length=256)

...

那你的 admin.py 文件 .

from.models import Profile
# Register your models here.


class ProfileAdmin(admin.ModelAdmin):
    model = Profile
    exclude = ['phone',] # Or whatever you don't want to display.

admin.site.register(Profile, ProfileAdmin)

对于扩展实施,请根据您的需要添加或删除 .

希望能帮助到你 .