python - 为 CustomUser 指定的未知字段(密码 1、密码 2)

标签 python django django-admin

Internal Server Error: /admin/account/customuser/add/
Traceback (most recent call last):
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\contrib\admin\options.py", line 642, in get_form
    return modelform_factory(self.model, **defaults)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\forms\models.py", line 543, in modelform_factory
    return type(form)(class_name, (form,), form_class_attrs)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\forms\models.py", line 252, in __new__
    raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (password2, password1) specified for CustomUser

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\core\handlers\exception.py", line 39, in inner
    response = get_response(request)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response
    response = self._get_response(request)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\contrib\admin\options.py", line 544, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\utils\decorators.py", line 149, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\views\decorators\cache.py", line 57, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\contrib\admin\sites.py", line 211, in inner
    return view(request, *args, **kwargs)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\utils\decorators.py", line 67, in _wrapper
    return bound_func(*args, **kwargs)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\views\decorators\debug.py", line 76, in sensitive_post_parameters_wrapper
    return view(request, *args, **kwargs)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\utils\decorators.py", line 63, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\utils\decorators.py", line 67, in _wrapper
    return bound_func(*args, **kwargs)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\utils\decorators.py", line 149, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\utils\decorators.py", line 63, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "C:\Users\Andriken\AppData\Local\Programs\Python\Python35\Lib\contextlib.py", line 30, in inner
    return func(*args, **kwds)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\contrib\auth\admin.py", line 128, in add_view
    extra_context)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\contrib\admin\options.py", line 1509, in add_view
    return self.changeform_view(request, None, form_url, extra_context)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\utils\decorators.py", line 67, in _wrapper
    return bound_func(*args, **kwargs)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\utils\decorators.py", line 149, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\utils\decorators.py", line 63, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "C:\Users\Andriken\AppData\Local\Programs\Python\Python35\Lib\contextlib.py", line 30, in inner
    return func(*args, **kwds)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\contrib\admin\options.py", line 1438, in changeform_view
    ModelForm = self.get_form(request, obj)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\contrib\auth\admin.py", line 82, in get_form
    return super(UserAdmin, self).get_form(request, obj, **defaults)
  File "C:\Users\Andriken\Documents\Prac\djangoexample\bookmarks\mysite_env\lib\site-packages\django\contrib\admin\options.py", line 646, in get_form
    % (e, self.__class__.__name__)
django.core.exceptions.FieldError: Unknown field(s) (password2, password1) specified for CustomUser. Check fields/fieldsets/exclude attributes of class CustomUserAdmin.
[07/Jul/2018 21:14:51] "GET /admin/account/customuser/add/ HTTP/1.1" 500 182719

forms.py --------------------------------------

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from account.models import CustomUser


class UserCreationForm(forms.ModelForm):
    password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
    password2 = forms.CharField(label='Repeat Password', widget=forms.PasswordInput)

    class Meta:
        fields = ('email','date_of_birth',)
        model= CustomUser

    def clean_password2(self):
        password1 = self.cleaned_data.get('password1')
        password2 = self.cleaned_data.get('password2')

        if password1 and password2 and password1 != password2:
            raise forms.ValidationError('Passwords don\'t match')
        return password2

    def save(self, commit=True):
        user = super(UserCreationForm, self).save(commit=False)
        user.set_password(self.cleaned_data['password2'])
        if commit:
            user.save()
        return user


class UserChangeForm(forms.ModelForm):
    password = ReadOnlyPasswordHashField()

class Meta:
    model = CustomUser
    fields = ('email','password','date_of_birth','is_active','is_admin')

def clean_password(self):
    return self.initial['password']

admin.py----------------

from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.contrib.auth.models import User
from account.forms import UserCreationForm, UserChangeForm, ExtendedUserCreationForm
from .models import CustomUser

在此处注册您的模型。

class CustomUserAdmin(BaseUserAdmin):
    form = UserCreationForm
    add_form = UserChangeForm
    # The fields to be used in displaying the User model.
    # These override the definitions on the base UserAdmin
    # that reference specific fields on auth.User.
    list_display = ('email', 'date_of_birth', 'is_admin','is_active')
    list_filter = ('is_admin',)
    fieldsets = (
        (None, {'fields': ('email', 'password')}),
        ('Personal info', {'fields': ('date_of_birth',)}),
        ('Permissions', {'fields': ('is_admin','is_active',)}),
    )
    # add_fieldsets is not a standard ModelAdmin attribute. UserAdmin
    # overrides get_fieldsets to use this attribute when creating a user.
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('date_of_birth','email','password1','password2')}
         ),
    )

    search_fields = ('email',)
    ordering = ('email',)
    filter_horizontal = ()



admin.site.register(CustomUser, CustomUserAdmin)
admin.site.unregister(Group)

请任何人尝试让我知道我在哪里遗漏了什么,我无法解决这个问题,我还尝试再次覆盖 Password1 和 Password2 字段的 UserCreationForm 以查看它是否有效,但没有成功。好像是一样的

最佳答案

在您的 CustomUserAdmin 中尝试切换 formadd_form

尝试:

class CustomUserAdmin(BaseUserAdmin):
    form = UserChangeForm
    add_form = UserCreationForm

add_form 用于创建新用户。 form 用于编辑

希望对您有所帮助。

关于python - 为 CustomUser 指定的未知字段(密码 1、密码 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51224764/

相关文章:

Python 不再看到 MySQLdb

python - 有什么方法可以更改管理面板中文本字段 django 的默认文本编辑器?

python - Django admin 中的间接内联

django - 在 Django 管理中,我如何隐藏或删除铅笔、 "+"和 "x"?

python - 写入文件 python - 换行问题 (\n)

python - 如何修复函数 'detectMultiScale' 中的 opencv/modules/objdetect/src/cascadedetect.cpp :1698: error: (-215:Assertion failed) ! empty() ^?

python - 将 Django 应用程序部署到 Azure VS2017 - 自定义 python

django - MacVim 中的错误命令输出

python - 使用 Python 将 CSV 转换为带有子列表数组的 JSON

django - Django digitalocean Spaces 请求的资源上不存在 'Access-Control-Allow-Origin' header