我正在开发一个自定义用户模型,它是AbstractBaseUser的子类,还有一个自定义模型管理器,它是BaseUserManager.This模型的子类,Employee,通过电子邮件地址进行身份验证- USERNAME_FIELD设置为email。
虽然我可以创建Employee实例并检查我的PosgreSQL DB以验证它们是否被保存,但我无法使用Django ORM和我的自定义模型管理器检索它们。如果我试图检索所有雇员,或者在运行Employee.objects.get(id=1)时“获取”一个雇员,我得到一个错误,from_db_value()需要4个参数,但收到5个参数。
我被难住了。我在另一个Django 1.11应用程序中有同样类型的自定义用户,并且工作正常。我花了两天的时间试图解决这个问题。有什么帮助吗?
models.py
from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser
)
from phone_field import PhoneField
from django.core.validators import RegexValidator
# to ensure leading zeroes are captured in badge number
numeric = RegexValidator(r'^[0-9]*$', 'Only numeric characters are allowed.')
# Create your models here.
class EmployeeManager(BaseUserManager):
def create_user(self, email, password=None):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, password):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.create_user(
email,
password=password,
)
user.is_admin = True
user.is_staff = True
user.save(using=self._db)
return user
class Employee(AbstractBaseUser):
email = models.EmailField(
verbose_name='email address',
max_length=255,
unique=True
)
# username = None
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = [] # email and password automatically required
objects = EmployeeManager()
BUSINESS_UNIT_CHOICES = [
('MKT', 'Marketing'),
('SLS', 'Sales'),
('OPS', 'Operations'),
('ADM', 'Adminstrative'),
]
DEPARTMENT_CHOICES = [
('EXT', 'Extraction'),
('PRD', 'Production'),
('QAL', 'Quality'),
('PRC', 'Procurement'),
]
LOCATION_CHOICES = [
('Menlo Park, CA', 'Menlo Park, California'),
('Santa Rosa, CA', 'Santa Rosa, California'),
]
badge_id = models.CharField(
max_length=4,
validators=[numeric],
)
bio = models.TextField(blank=True, null=True)
business_unit = models.CharField(
blank=True,
null=True,
choices=BUSINESS_UNIT_CHOICES,
max_length=3,
unique=False
)
department = models.CharField(
blank=True,
null=True,
choices=DEPARTMENT_CHOICES,
max_length=3,
unique=False
)
first_name = models.CharField(
blank=True,
null=True,
max_length=255
)
last_name = models.CharField(
blank=True,
null=True,
max_length=255,
)
phone = PhoneField(
blank=True,
null=True,
verbose_name='phone number',
help_text='Contact phone number'
)
job_title = models.CharField(
blank=True,
null=True,
max_length=255,
unique=False
)
hire_date = models.DateField(auto_now_add=True)
location = models.CharField(
blank=True,
null=True,
choices=LOCATION_CHOICES,
max_length=255,
unique=False,
)
# password field is builtin
is_active = models.BooleanField(default=True)
is_admin = models.BooleanField(default=False)
is_staff = models.BooleanField(default=False)
def __str__(self):
return self.email
def get_full_name(self):
return F"{self.first_name} {self.last_name}"
def get_short_name(self):
return self.first_name
def get_phone_number(self):
return self.phone
def get_business_unit(self):
return self.business_unit
def get_job_title(self):
return self.job_title
def get_location(self):
return self.location
def has_perm(self, perm, obj=None):
# does user have permissions?
return True
def has_module_perms(self, app_label):
return Truesettings.py (项目级)
"""
Django settings for andromeda project.
Generated by 'django-admin startproject' using Django 1.11.17.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/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/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '1w$d2y4#jmv_763ea3=lj=hjgyu3l^8!fpcy%t%lcj0+yuuoo='
# 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',
'accounts',
]
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',
]
ROOT_URLCONF = 'andromeda.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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 = 'andromeda.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ['DB_NAME'],
'USER': os.environ['DB_USER'],
'PASSWORD': os.environ['DB_USER_PW'],
'HOST': 'localhost',
'PORT': '',
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/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/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'America/Los_Angeles'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
AUTH_USER_MODEL = 'accounts.Employee'
AUTHENTICATION_BACKENDS = ('accounts.backends.EmployeeAuth','django.contrib.auth.backends.ModelBackend',)堆栈跟踪
>>> e = Employee.objects.get(id=1)
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/opt/miniconda3/envs/django-dev/lib/python3.7/site-packages/django/db/models/manager.py", line 85, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/opt/miniconda3/envs/django-dev/lib/python3.7/site-packages/django/db/models/query.py", line 374, in get
num = len(clone)
File "/opt/miniconda3/envs/django-dev/lib/python3.7/site-packages/django/db/models/query.py", line 232, in __len__
self._fetch_all()
File "/opt/miniconda3/envs/django-dev/lib/python3.7/site-packages/django/db/models/query.py", line 1121, in _fetch_all
self._result_cache = list(self._iterable_class(self))
File "/opt/miniconda3/envs/django-dev/lib/python3.7/site-packages/django/db/models/query.py", line 62, in __iter__
for row in compiler.results_iter(results):
File "/opt/miniconda3/envs/django-dev/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 847, in results_iter
row = self.apply_converters(row, converters)
File "/opt/miniconda3/envs/django-dev/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 832, in apply_converters
value = converter(value, expression, self.connection, self.query.context)
TypeError: from_db_value() takes 4 positional arguments but 5 were given
>>>编辑#1:弄清楚了- django-phone-field模块正在制造问题。
发布于 2019-11-20 03:11:17
删除django phone_field解决了这个问题。现在,我可以使用ORM从Db中获取Mode实例
https://stackoverflow.com/questions/58926170
复制相似问题