尝试 Django 迁移生成错误:"Unknown field(s) (groups) specified for User"



我在学习如何将自定义用户模型合并到我的 Wagtail 应用程序中时遇到了这个问题。当我尝试运行时会发生此错误:python manage.py makemigrations.同样值得注意的是,我没有向 admin.py 和 forms.py 添加任何代码,因为我需要在取得任何进一步进展之前查看此迁移工作。 我已经在网上搜索了任何此类错误,最接近我自己的错误是:Django - 为用户指定的未知字段(组(。
然而,似乎作者和受访者也被难住了。
我需要知道这是否是一个鹡鸰问题,如果是这样,有没有人对如何解决/规避这个问题有任何想法?
这是我的代码:

帐户/模型.py

from django.db import models
# Create your models here.
from django.db import models
from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
)
# Create your models here.
class UserManager(BaseUserManager):
def create_user(self, email, password=None, is_active=True, is_staff=False, is_admin=False): #add required_fields in here too
if not email:
raise ValueError("Users must have an Email Address")
if not password:
raise ValueError("Users must have a Password")
user = self.model(
email=self.normalize_email(email)
)
user.set_password(password)
user.active = is_active
user.staff = is_staff
user.admin = is_admin
user.save(using=self._db)
return user
def create_staffuser(self, email, password=None):
user = self.create_user(
email,
password=password,
is_staff=True
)
user.save(using=self._db)
return user
def create_superuser(self, email, password=None):
user = self.create_user(
email,
password=password,
is_staff=True,
is_admin=True
)
user.save(using=self._db)
return user
class User(AbstractBaseUser):
"""
Custom User that will be an alternative to the Django default User
"""
email= models.EmailField(max_length=100, unique=True) # db_index=True
active= models.BooleanField(default=True) # can the user login?
staff= models.BooleanField(default=False) #staff
admin= models.BooleanField(default=False) # admin of our site
timestamp= models.DateTimeField(auto_now_add=True)
USERNAME_FIELD = 'email' # this will take the place of username field
REQUIRED_FIELDS = []  # Effected during python manage.py createsuperuser
objects = UserManager()
def __str__(self):
return self.email
def get_full_name(self):
return self.email
def get_short_name(self):
return self.email

@property
def is_active(self):
return self.active
@property
def is_staff(self):
return self.staff
@property
def is_admin(self):
return self.admin

设置/基础.py

"""
Django settings for sch_admin project.
Generated by 'django-admin startproject' using Django 2.2.1.
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/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(PROJECT_DIR)

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# Application definition
INSTALLED_APPS = [
'home',
'search',
'wagtail.contrib.forms',
'wagtail.contrib.redirects',
'wagtail.embeds',
'wagtail.sites',
'wagtail.users',
'wagtail.snippets',
'wagtail.documents',
'wagtail.images',
'wagtail.search',
'wagtail.admin',
'wagtail.core',
'modelcluster',
'taggit',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# custom apps
'accounts.apps.AccountsConfig',
]
AUTH_USER_MODEL = 'accounts.User'  # changes built-in user model to our custom one
MIDDLEWARE = [
'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',
'django.middleware.security.SecurityMiddleware',
'wagtail.core.middleware.SiteMiddleware',
'wagtail.contrib.redirects.middleware.RedirectMiddleware',
]
ROOT_URLCONF = 'sch_admin.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(PROJECT_DIR, '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 = 'sch_admin.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'sqlite': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
},
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ.get('DBWORKNAME'),
'USER': os.environ.get('DBWORKUSER'),
'PASSWORD': os.environ.get('DBWORKPASSWORD'),
'HOST': os.environ.get('DBWORKHOST'),
}
}

DATABASE_ROUTES = [
'sch_src.router.NonMinerDevAttributeRouter'     # Router's module path
]

# 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 = 'en-us'
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/
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
STATICFILES_DIRS = [
os.path.join(PROJECT_DIR, 'static'),
]
# ManifestStaticFilesStorage is recommended in production, to prevent outdated
# Javascript / CSS assets being served from cache (e.g. after a Wagtail upgrade).
# See https://docs.djangoproject.com/en/2.2/ref/contrib/staticfiles/#manifeststaticfilesstorage
STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

# Wagtail settings
WAGTAIL_SITE_NAME = "sch_admin"
# Base URL to use when referring to full URLs within the Wagtail admin backend -
# e.g. in notification emails. Don't include '/admin' or a trailing slash
BASE_URL = 'http://example.com'
# logging functionality
import logging.config
LOGGING_CONFIG = None
logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
# exact format is not important, this is the minimum information
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s',
},
'simple': {
'format': '%(levelname)s %(message)s',
},
},
'handlers': {
'console': {
'class': 'logging.StreamHandler',
'level':'DEBUG',
'formatter': 'simple',
},
'file': {
'level': 'DEBUG',
'class': 'logging.FileHandler',
'filename': os.path.join(BASE_DIR, 'logs/lumberjack.log'),
'formatter':'verbose',
},
},
'loggers': {
# below is the root logger - handles any logs sent from any python module
'': {
'level': 'INFO',
'handlers': ['console', 'file'],
},
},
})

遇到错误:

Traceback (most recent call last):
File "C:Program FilesJetBrainsPyCharm 2018.1.4helperspycharmdjango_manage.py", line 52, in <module>
run_command()
File "C:Program FilesJetBrainsPyCharm 2018.1.4helperspycharmdjango_manage.py", line 46, in run_command
run_module(manage_file, None, '__main__', True)
File "C:Python36librunpy.py", line 205, in run_module
return _run_module_code(code, init_globals, run_name, mod_spec)
File "C:Python36librunpy.py", line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File "C:Python36librunpy.py", line 85, in _run_code
exec(code, run_globals)
File "C:/baronprojects/pythonprojects/djangoprojects/sch_mgmt_project/sch_srcmanage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "C:Python36libsite-packagesdjangocoremanagement__init__.py", line 381, in execute_from_command_line
utility.execute()
File "C:Python36libsite-packagesdjangocoremanagement__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:Python36libsite-packagesdjangocoremanagementbase.py", line 323, in run_from_argv
self.execute(*args, **cmd_options)
File "C:Python36libsite-packagesdjangocoremanagementbase.py", line 361, in execute
self.check()
File "C:Python36libsite-packagesdjangocoremanagementbase.py", line 390, in check
include_deployment_checks=include_deployment_checks,
File "C:Python36libsite-packagesdjangocoremanagementbase.py", line 377, in _run_checks
return checks.run_checks(**kwargs)
File "C:Python36libsite-packagesdjangocorechecksregistry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "C:Python36libsite-packagesdjangocorechecksurls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:Python36libsite-packagesdjangocorechecksurls.py", line 23, in check_resolver
return check_method()
File "C:Python36libsite-packagesdjangourlsresolvers.py", line 398, in check
for pattern in self.url_patterns:
File "C:Python36libsite-packagesdjangoutilsfunctional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:Python36libsite-packagesdjangourlsresolvers.py", line 579, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:Python36libsite-packagesdjangoutilsfunctional.py", line 80, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:Python36libsite-packagesdjangourlsresolvers.py", line 572, in urlconf_module
return import_module(self.urlconf_name)
File "C:Python36libimportlib__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:/baronprojects/pythonprojects/djangoprojects/sch_mgmt_project/sch_srcsch_adminurls.py", line 5, in <module>
from wagtail.admin import urls as wagtailadmin_urls
File "C:Python36libsite-packageswagtailadminurls__init__.py", line 11, in <module>
from wagtail.admin.urls import password_reset as wagtailadmin_password_reset_urls
File "C:Python36libsite-packageswagtailadminurlspassword_reset.py", line 3, in <module>
from wagtail.admin.views import account
File "C:Python36libsite-packageswagtailadminviewsaccount.py", line 14, in <module>
from wagtail.users.forms import (
File "C:Python36libsite-packageswagtailusersforms.py", line 178, in <module>
class UserCreationForm(UserForm):
File "C:Python36libsite-packagesdjangoformsmodels.py", line 266, in __new__
raise FieldError(message)
django.core.exceptions.FieldError: Unknown field(s) (groups) specified for User

对于那些在将来专门使用 Django 或 Wagtail 时可能会遇到相同错误的人,我找到了这个特定问题的解决方案:https://docs.wagtail.io/en/v2.7/getting_started/integrating_into_django.html#user-accounts .
这句话让我印象深刻:

Custom user models are supported, with some restrictions;   
Wagtail uses an extension of Django’s permissions framework,   
so your user model must at minimum inherit from AbstractBaseUser and PermissionsMixin.

显然,一个人需要从AbstractBaseUserPermissionsMixin继承,即:

from django.contrib.auth.models import (
AbstractBaseUser,
BaseUserManager,
PermissionsMixin,
)
class User(AbstractBaseUser, PermissionsMixin):
# insert other code here 
  • 完成此操作后,我能够使用命令python manage.py makemigrations以及python manage.py migrate

供进一步参考:
* 迁移:

manage.py@sch_src > makemigrations
Tracking file by folder pattern:  migrations
Migrations for 'accounts':
accountsmigrations001_initial.py
- Create model User
Following files were affected 
C:baronprojectspythonprojectsdjangoprojectssch_mgmt_projectsch_src  
accountsmigrations001_initial.py
Process finished with exit code 0
  • 迁移:
manage.py@sch_src > migrate
Tracking file by folder pattern:  migrations
Operations to perform:
Apply all migrations: accounts, admin, auth, contenttypes, home, sessions, taggit, wagtailadmin, wagtailcore, wagtaildocs, wagtailembeds, wagtailforms, wagtailimages, wagtailredirects, wagtailsearch, wagtailusers
Running migrations:
Applying contenttypes.0001_initial... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0001_initial... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying auth.0007_alter_validators_add_error_messages... OK
Applying auth.0008_alter_user_username_max_length... OK
Applying auth.0009_alter_user_last_name_max_length... OK
Applying auth.0010_alter_group_name_max_length... OK
Applying auth.0011_update_proxy_permissions... OK
Applying accounts.0001_initial... OK
Applying admin.0001_initial... OK
Applying admin.0002_logentry_remove_auto_add... OK
Applying admin.0003_logentry_add_action_flag_choices... OK
Applying wagtailcore.0001_squashed_0016_change_page_url_path_to_text_field... OK
Applying wagtailcore.0017_change_edit_page_permission_description... OK
Applying wagtailcore.0018_pagerevision_submitted_for_moderation_index... OK
Applying wagtailcore.0019_verbose_names_cleanup... OK
Applying wagtailcore.0020_add_index_on_page_first_published_at... OK
Applying wagtailcore.0021_capitalizeverbose... OK
Applying wagtailcore.0022_add_site_name... OK
Applying wagtailcore.0023_alter_page_revision_on_delete_behaviour... OK
Applying wagtailcore.0024_collection... OK
Applying wagtailcore.0025_collection_initial_data... OK
Applying wagtailcore.0026_group_collection_permission... OK
Applying wagtailcore.0027_fix_collection_path_collation... OK
Applying wagtailcore.0024_alter_page_content_type_on_delete_behaviour... OK
Applying wagtailcore.0028_merge... OK
Applying wagtailcore.0029_unicode_slugfield_dj19... OK
Applying wagtailcore.0030_index_on_pagerevision_created_at... OK
Applying wagtailcore.0031_add_page_view_restriction_types... OK
Applying wagtailcore.0032_add_bulk_delete_page_permission... OK
Applying wagtailcore.0033_remove_golive_expiry_help_text... OK
Applying wagtailcore.0034_page_live_revision... OK
Applying wagtailcore.0035_page_last_published_at... OK
Applying wagtailcore.0036_populate_page_last_published_at... OK
Applying wagtailcore.0037_set_page_owner_editable... OK
Applying wagtailcore.0038_make_first_published_at_editable... OK
Applying wagtailcore.0039_collectionviewrestriction... OK
Applying wagtailcore.0040_page_draft_title... OK
Applying home.0001_initial... OK
Applying home.0002_create_homepage... OK
Applying sessions.0001_initial... OK
Applying taggit.0001_initial... OK
Applying taggit.0002_auto_20150616_2121... OK
Applying wagtailadmin.0001_create_admin_access_permissions... OK
Applying wagtailcore.0041_group_collection_permissions_verbose_name_plural... OK
Applying wagtaildocs.0001_initial... OK
Applying wagtaildocs.0002_initial_data... OK
Applying wagtaildocs.0003_add_verbose_names... OK
Applying wagtaildocs.0004_capitalizeverbose... OK
Applying wagtaildocs.0005_document_collection... OK
Applying wagtaildocs.0006_copy_document_permissions_to_collections... OK
Applying wagtaildocs.0005_alter_uploaded_by_user_on_delete_action... OK
Applying wagtaildocs.0007_merge... OK
Applying wagtaildocs.0008_document_file_size... OK
Applying wagtaildocs.0009_document_verbose_name_plural... OK
Applying wagtaildocs.0010_document_file_hash... OK
Applying wagtailembeds.0001_initial... OK
Applying wagtailembeds.0002_add_verbose_names... OK
Applying wagtailembeds.0003_capitalizeverbose... OK
Applying wagtailembeds.0004_embed_verbose_name_plural... OK
Applying wagtailembeds.0005_specify_thumbnail_url_max_length... OK
Applying wagtailforms.0001_initial... OK
Applying wagtailforms.0002_add_verbose_names... OK
Applying wagtailforms.0003_capitalizeverbose... OK
Applying wagtailimages.0001_squashed_0021... OK
Applying wagtailredirects.0001_initial... OK
Applying wagtailredirects.0002_add_verbose_names... OK
Applying wagtailredirects.0003_make_site_field_editable... OK
Applying wagtailredirects.0004_set_unique_on_path_and_site... OK
Applying wagtailredirects.0005_capitalizeverbose... OK
Applying wagtailredirects.0006_redirect_increase_max_length... OK
Applying wagtailsearch.0001_initial... OK
Applying wagtailsearch.0002_add_verbose_names... OK
Applying wagtailsearch.0003_remove_editors_pick... OK
Applying wagtailsearch.0004_querydailyhits_verbose_name_plural... OK
Applying wagtailusers.0001_initial... OK
Applying wagtailusers.0002_add_verbose_name_on_userprofile... OK
Applying wagtailusers.0003_add_verbose_names... OK
Applying wagtailusers.0004_capitalizeverbose... OK
Applying wagtailusers.0005_make_related_name_wagtail_specific... OK
Applying wagtailusers.0006_userprofile_prefered_language... OK
Applying wagtailusers.0007_userprofile_current_time_zone... OK
Applying wagtailusers.0008_userprofile_avatar... OK
Applying wagtailusers.0009_userprofile_verbose_name_plural... OK

相关内容

  • 没有找到相关文章

最新更新