我创建了一个自定义用户模型和admin模型,当我尝试从admin创建新用户时,出现此错误:
/ admin / account / myuser / add /
处的NotImplementedError
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/account/myuser/add/
Django Version: 2.2
Python Version: 3.7.1
Installed Applications:
['django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'account.apps.AccountConfig',
'debug_toolbar']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware']
Traceback:
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\djongo\sql2mongo\query.py" in parse
799. handler = self.FUNC_MAP[sm_type]
During handling of the above exception ('UNKNOWN'), another exception occurred:
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\contrib\admin\options.py" in wrapper
606. return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\utils\decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\views\decorators\cache.py" in _wrapped_view_func
44. response = view_func(request, *args, **kwargs)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\contrib\admin\sites.py" in inner
223. return view(request, *args, **kwargs)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\utils\decorators.py" in _wrapper
45. return bound_method(*args, **kwargs)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\views\decorators\debug.py" in sensitive_post_parameters_wrapper
76. return view(request, *args, **kwargs)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\utils\decorators.py" in _wrapper
45. return bound_method(*args, **kwargs)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\utils\decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\contrib\auth\admin.py" in add_view
99. return self._add_view(request, form_url, extra_context)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\contrib\auth\admin.py" in _add_view
126. return super().add_view(request, form_url, extra_context)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\contrib\admin\options.py" in add_view
1634. return self.changeform_view(request, None, form_url, extra_context)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\utils\decorators.py" in _wrapper
45. return bound_method(*args, **kwargs)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\utils\decorators.py" in _wrapped_view
142. response = view_func(request, *args, **kwargs)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\contrib\admin\options.py" in changeform_view
1521. with transaction.atomic(using=router.db_for_write(self.model)):
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\db\transaction.py" in __enter__
196. sid = connection.savepoint()
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\db\backends\base\base.py" in savepoint
332. self._savepoint(sid)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\db\backends\base\base.py" in _savepoint
300. cursor.execute(self.ops.savepoint_create_sql(sid))
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\debug_toolbar\panels\sql\tracking.py" in execute
186. return self._record(self.cursor.execute, sql, params)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\debug_toolbar\panels\sql\tracking.py" in _record
124. return method(sql, params)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\db\backends\utils.py" in execute
99. return super().execute(sql, params)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\db\backends\utils.py" in execute
67. return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\db\backends\utils.py" in _execute_with_wrappers
76. return executor(sql, params, many, context)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\django\db\backends\utils.py" in _execute
82. return self.cursor.execute(sql)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\djongo\cursor.py" in execute
53. params)
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\djongo\sql2mongo\query.py" in __init__
743. self.parse()
File "C:\Users\hanan\Documents\GitHub\Predictive_maintenance\venv\lib\site-packages\djongo\sql2mongo\query.py" in parse
802. raise NotImplementedError(f'{sm_type} command not implemented for SQL {self._sql}')
Exception Type: NotImplementedError at /admin/account/myuser/add/
Exception Value: UNKNOWN command not implemented for SQL SAVEPOINT "s5560_x1"
class MyUserManager(BaseUserManager):
def create_user(self, email, date_of_birth, password=None):
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
date_of_birth=date_of_birth,
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, date_of_birth, password):
user = self.create_user(email,
password=password,
date_of_birth=date_of_birth
)
user.is_admin = True
user.save(using=self._db)
return user
class MyUser(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True,
)
date_of_birth = models.DateField()
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
role= models.CharField(max_length=100)
objects = MyUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['date_of_birth']
from django import forms
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.forms import ReadOnlyPasswordHashField
from account.models import MyUser
class UserCreationForm(forms.ModelForm):
"""A form for creating new users. Includes all the required
fields, plus a repeated password."""
password1 = forms.CharField(label='Password', widget=forms.PasswordInput)
password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput)
class Meta:
model = MyUser
fields = ('email', 'date_of_birth')
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):
# Save the provided password in hashed format
user = super(UserCreationForm, self).save(commit=False)
user.set_password(self.cleaned_data["password1"])
if commit:
user.save()
return user
class UserChangeForm(forms.ModelForm):
password = ReadOnlyPasswordHashField()
class Meta:
model = MyUser
fields = ('email', 'password', 'date_of_birth', 'is_active', 'is_admin')
def clean_password(self):
return self.initial["password"]
class UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
# 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')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password')}),
('Personal info', {'fields': ('date_of_birth',)}),
('Permissions', {'fields': ('is_admin',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'date_of_birth', 'password1', 'password2')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
admin.site.register(MyUser, UserAdmin)
admin.site.unregister(Group)
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 2.2.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'pme5tk0(%744prm2jioq^y4h4$=8$_%n&sp)bhhvvi-8-z!a)n'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'account.apps.AccountConfig',
'debug_toolbar',
]
#LOGIN_URL = '/login/'
######################### AUTH ############################
AUTH_USER_MODEL = 'account.MyUser'
#AUTHENTICATION_BACKENDS = ('account.backends.CustomUserAuth',)
########################################################
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['C:/Users/hanan/Documents/GitHub/Predictive_maintenance/account/templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'djongo',
'NAME': 'smtbdd',
'HOST':'localhost',
'PORT':27017,
}
}
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/
LANGUAGE_CODE = 'fr'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/
STATIC_URL = '/static/'
#STATIC_ROOT = os.path.join(BASE_DIR, "static")
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'static')
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'), # Here you tell django to look for a folder named 'assets'
]
INTERNAL_IPS=['127.0.0.1']
当我将以下行:admin.site.register(MyUser, UserAdmin)
更改为以下行:admin.site.register(MyUser)
时,我可以创建用户,但密码不会在数据库中散列。
问题不在代码中,而是在Django版本中,我刚刚降级到Django 2.1.8版本(从2.2版开始),问题已解决;)