类型对象'multichoice'没有属性'_default_manager'

Posted

技术标签:

【中文标题】类型对象\'multichoice\'没有属性\'_default_manager\'【英文标题】:type object 'multichoice' has no attribute '_default_manager'类型对象'multichoice'没有属性'_default_manager' 【发布时间】:2021-08-01 12:41:35 【问题描述】:

我正在使用 Django 和 mongoengine。管理面板无法在multichoice 模型中添加数据我收到此错误。 type object 'multichoice' has no attribute '_default_manager' Python 版本:3.9.2 Django 版本:3、0、5、'final'、0模型

from mongoengine import Document, fields
# Create your models here.
class multichoice(Document):
    m_class_choices = [('5_c', '5th Class'), ('6_c', '6th Class'), ('7_c', '7th Class'), ('8_c', '8th Class')]
    m_subject_choice = [('accounting','Accounting'), ('bus-math','Business-Math'), ('stats','Statistics'),]
    m_language_choice = [('en', 'English'), ('fr', 'French',)]
    m_type_choice = [('paper', 'Past Paper'), ('book', 'Book'),]
    
    m_title = fields.StringField(primary_key=True, max_length=255, default='A')
    m_slug = fields.StringField(default='a')
    m_question = fields.StringField(default='A')
    m_question_number = fields.StringField(max_length=255, default='1')
    m_alternatives = fields.ListField(default='A')
    m_class = fields.StringField(choices=m_class_choices, max_length=10, default='5_c')
    m_subject = fields.StringField(choices=m_subject_choice, max_length=50, default='accounting')
    m_lan = fields.StringField(choices=m_language_choice, max_length=2, default='en')
    m_type = fields.StringField(choices=m_type_choice, max_length=5, default='book')
    m_unit = fields.IntField(min_value=1, max_value=99, default='1')
    m_paper_year = fields.IntField(min_value=1990, max_value=2050, default='2021')

    def __str__(self):
        return self.m_title

管理员

from django_mongoengine import mongo_admin as admin
from mcqs.models import *

# Register your models here.
class multichoice_admin(admin.DocumentAdmin):
    model = multichoice
    fields = ('m_title', 'm_slug', 'm_question', 'm_question_number', 'm_alternatives', 'm_class', 'm_subject', 'm_lan', 'm_type', 'm_unit', 'm_paper_year', )


admin.site.register(multichoice, multichoice_admin)

网址

from django.contrib import admin
from django.urls import path
from django_mongoengine import mongo_admin

urlpatterns = [
    path('admin/', admin.site.urls),
    path('content_admin/', mongo_admin.site.urls),
]

设置

"""
Django settings for djangoquizapp project.

Generated by 'django-admin startproject' using Django 3.0.5.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/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/3.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'cj7vupw+e#lzp-^t3_j7lh6ieuh9%3k2iupp(+fdn_d5xq8=qn'

# 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',
    'django_mongoengine',
    'django_mongoengine.mongo_auth',
    'django_mongoengine.mongo_admin',
    'mcqs',
]

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 = 'djangoquizapp.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 = 'djangoquizapp.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases

# MongoDB Databases
MONGODB_DATABASES = 
    'default': 'name': 'djangoquizapp'


DATABASES = 
    'default': 
        'ENGINE': 'djongo',
        'NAME': 'djangoquizapp',
    



# Password validation
# https://docs.djangoproject.com/en/3.0/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/3.0/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/3.0/howto/static-files/

STATIC_URL = '/static/'

编辑 1

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/content_admin/mcqs/multichoice/add/

Django Version: 3.0.5
Python Version: 3.9.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django_mongoengine',
 'django_mongoengine.mongo_auth',
 'django_mongoengine.mongo_admin',
 'mcqs']
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']



Traceback (most recent call last):
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\contrib\admin\options.py", line 607, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\contrib\admin\sites.py", line 231, in inner
    return view(request, *args, **kwargs)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\contrib\admin\options.py", line 1638, in add_view
    return self.changeform_view(request, None, form_url, extra_context)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\utils\decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "C:\Program Files\Python39\lib\site-packages\django_mongoengine\mongo_admin\options.py", line 306, in changeform_view
    ModelForm = self.get_form(request, obj)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\contrib\admin\options.py", line 702, in get_form
    return modelform_factory(self.model, **defaults)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\forms\models.py", line 554, in modelform_factory
    return type(form)(class_name, (form,), form_class_attrs)
  File "C:\Program Files\Python39\lib\site-packages\django_mongoengine\forms\documents.py", line 136, in __new__
    fields = model_forms.fields_for_model(
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\forms\models.py", line 178, in fields_for_model
    formfield = formfield_callback(f, **kwargs)
  File "C:\Program Files\Python39\lib\site-packages\django_mongoengine\mongo_admin\options.py", line 111, in formfield_for_dbfield
    return db_field.formfield(**kwargs)
  File "C:\Program Files\Python39\lib\site-packages\django_mongoengine\fields\djangoflavor.py", line 247, in formfield
    if self.field.choices:

Exception Type: AttributeError at /content_admin/mcqs/multichoice/add/
Exception Value: 'NoneType' object has no attribute 'choices'

编辑 2

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/content_admin/mcqs/multichoice/add/

Django Version: 3.0.5
Python Version: 3.9.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django_mongoengine',
 'django_mongoengine.mongo_auth',
 'django_mongoengine.mongo_admin',
 'mcqs']
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']



Traceback (most recent call last):
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\contrib\admin\options.py", line 607, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\contrib\admin\sites.py", line 231, in inner
    return view(request, *args, **kwargs)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\contrib\admin\options.py", line 1638, in add_view
    return self.changeform_view(request, None, form_url, extra_context)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\utils\decorators.py", line 43, in _wrapper
    return bound_method(*args, **kwargs)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\utils\decorators.py", line 130, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "C:\Program Files\Python39\lib\site-packages\django_mongoengine\mongo_admin\options.py", line 306, in changeform_view
    ModelForm = self.get_form(request, obj)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\contrib\admin\options.py", line 702, in get_form
    return modelform_factory(self.model, **defaults)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\forms\models.py", line 554, in modelform_factory
    return type(form)(class_name, (form,), form_class_attrs)
  File "C:\Program Files\Python39\lib\site-packages\django_mongoengine\forms\documents.py", line 136, in __new__
    fields = model_forms.fields_for_model(
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\forms\models.py", line 178, in fields_for_model
    formfield = formfield_callback(f, **kwargs)
  File "C:\Program Files\Python39\lib\site-packages\django_mongoengine\mongo_admin\options.py", line 74, in formfield_for_dbfield
    return self.formfield_for_choice_field(db_field, request, **kwargs)
  File "C:\Program Files\Python39\lib\site-packages\django_mongoengine\mongo_admin\options.py", line 129, in formfield_for_choice_field
    return db_field.formfield(**kwargs)
  File "C:\Program Files\Python39\lib\site-packages\django_mongoengine\fields\djangoflavor.py", line 134, in formfield
    return super(StringField, self).formfield(form_class, choices_form_class, **defaults)
  File "C:\Program Files\Python39\lib\site-packages\django_mongoengine\fields\djangoflavor.py", line 65, in formfield
    defaults['choices'] = self.get_choices(include_blank=include_blank)
  File "C:\Users\Ali Abdullah\AppData\Roaming\Python\Python39\site-packages\django\db\models\fields\__init__.py", line 850, in get_choices
    blank_defined = any(choice in ('', None) for choice, _ in self.flatchoices)

Exception Type: AttributeError at /content_admin/mcqs/multichoice/add/
Exception Value: 'StringField' object has no attribute 'flatchoices'

【问题讨论】:

出现错误的代码在哪里?它可能是视图文件,所以您也可以共享视图文件吗?此外,设置文件看起来有点缺失。 我的视图中没有任何内容。另外,我添加了完整的设置文件。 【参考方案1】:

您必须从 django_mongoengine 导入 Document 而不是 mongoengine:

from django_mongoengine import Document, EmbeddedDocument, fields

见README.rst > Documents


也如source of django-mongoengine中所述管理员部分支持

工作/Django 2.0-3.0

[ok] 会话 [ok] 模型/字段,字段需要测试 [ok] 观看次数 [ok] 授权 [?] 管理员 - 部分工作,有些东西坏了

同样来自README.rst

警告:也许有更好的 mongo 支持选项,看看 **https://nesdis.github.io/djongo/**; 它只是 python3,我有 还没试过,但看起来很有希望。

更新您的下一个错误。

您必须向您的 ListField 添加选项,例如:

from django_mongoengine import Document, EmbeddedDocument, fields

class multichoice(Document):
    ALTERNATIVES = (('al1', 'Alternative 1'), ('al2', 'Alternative 2'))
    ...other fields...
    m_alternatives = fields.ListField(fields.StringField(choices=ALTERNATIVES), help_text=_("""My alternatives"""))

Embedded Fields

【讨论】:

我需要 List 字段(mongodb 中每个问题的数组来存储所有选择)。 Djongo 不支持它 @Aly,无论如何你必须从django_mongoengine而不是mongoengine导入。 同样的错误现在是'NoneType' object has no attribute 'choices' @Aly,这不是同样的错误。请显示完整的回溯。 不,mongoengine 不支持mongo_admin

以上是关于类型对象'multichoice'没有属性'_default_manager'的主要内容,如果未能解决你的问题,请参考以下文章

获取属性错误:类型对象“Level_2_Headings”没有属性“祖先”(GAE 数据存储)

AttributeError:类型对象“产品”没有属性“_meta”

pyudev 类型对象“上下文”没有属性“_libudev”

AttributeError:类型对象“numpy.ndarray”没有属性“__array_function__”

AttributeError:类型对象“问题”没有属性“实际问题”[关闭]

AttributeError:类型对象“sklearn.tree._tree.TreeBuilder”没有属性“__reduce_cython__”