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

时间:2018-04-18 08:07:13

标签: django django-models django-forms

我创建了自定义模型Profile并将其链接到用户模型,该模型工作正常。但是,现在我想在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 个答案:

答案 0 :(得分:1)

首先,您的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)

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

希望它有所帮助。