快速入门文档中的Django REST框架中/'OrderedDict'对象的AttributeError没有属性'register'

时间:2019-08-13 14:00:53

标签: python django django-rest-framework

我正在尝试使用Django REST框架,但是在/ 'OrderedDict'对象没有属性'register'。 我认为我已经正确遵循了文档说明,有人可以帮忙吗?

链接到本教程:https://www.django-rest-framework.org/tutorial/quickstart/

我已经使用过Django,现在我正在尝试使用Django REST框架,但是按照快速入门教程进行操作会导致: /的AttributeError “ OrderedDict”对象没有“ register”属性。

tutorial.py/urls.py

from rest_framework import routers
from quickstart import views

from django.contrib import admin

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

tutorial/quickstart/serializers.py

from rest_framework import serializers


class UserSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ['url', 'username', 'email', 'groups']


class GroupSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Group
        fields = ['url', 'name']

tutorial/quickstart/views.py

from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from .serializers import UserSerializer, GroupSerializer


class UserViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer

tutorial/settings.py

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 = '&m8r-k(#%7tw6u31r-83ld_3@uw+86xrztepov4&=+s(&uapy2'

# 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',
    'rest_framework',
]

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


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

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}


# 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_URL = '/static/'

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}

错误响应为:

Environment:


Request Method: GET
Request URL: http://127.0.0.1:8000/

Django Version: 2.2.3
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',
 'rest_framework']
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:

File "D:\ProgrammingFiles\lib\site-packages\django\core\handlers\exception.py" in inner
  34.             response = get_response(request)

File "D:\ProgrammingFiles\lib\site-packages\django\core\handlers\base.py" in _get_response
  145.                 response = self.process_exception_by_middleware(e, request)

File "D:\ProgrammingFiles\lib\site-packages\django\core\handlers\base.py" in _get_response
  143.                 response = response.render()

File "D:\ProgrammingFiles\lib\site-packages\django\template\response.py" in render
  106.             self.content = self.rendered_content

File "D:\ProgrammingFiles\lib\site-packages\rest_framework\response.py" in rendered_content
  70.         ret = renderer.render(self.data, accepted_media_type, context)

File "D:\ProgrammingFiles\lib\site-packages\rest_framework\renderers.py" in render
  725.         context = self.get_context(data, accepted_media_type, renderer_context)

File "D:\ProgrammingFiles\lib\site-packages\rest_framework\renderers.py" in get_context
  687.             'description': self.get_description(view, response.status_code),

File "D:\ProgrammingFiles\lib\site-packages\rest_framework\renderers.py" in get_description
  602.         return view.get_view_description(html=True)

File "D:\ProgrammingFiles\lib\site-packages\rest_framework\views.py" in get_view_description
  245.         return func(self, html)

File "D:\ProgrammingFiles\lib\site-packages\rest_framework\views.py" in get_view_description
  61.         return formatting.markup_description(description)

File "D:\ProgrammingFiles\lib\site-packages\rest_framework\utils\formatting.py" in markup_description
  63.         description = apply_markdown(description)

File "D:\ProgrammingFiles\lib\site-packages\rest_framework\compat.py" in apply_markdown
  156.         md_filter_add_syntax_highlight(md)

File "D:\ProgrammingFiles\lib\site-packages\rest_framework\compat.py" in md_filter_add_syntax_highlight
  213.         md.preprocessors.register(CodeBlockPreprocessor(), 'highlight', 40)

Exception Type: AttributeError at /
Exception Value: 'OrderedDict' object has no attribute 'register'

结果应为: https://www.django-rest-framework.org/img/quickstart.png

4 个答案:

答案 0 :(得分:7)

您安装的markdown库的版本与您使用的Django REST Framework的版本不兼容。

markdown库至少更新为3.0,以解决此问题。

编辑:如评论中所述,如果您安装了markdown 3.1,则您的Python解释器可能会选择安装在其他位置的旧版本。

您可以通过导入并检查markdown.__file__markdown.version来检查解释器选择的降价版本。

最可靠的方法可能是将这些行添加到您的settings.py

import markdown
print('Markdown module path', markdown.__file__)
print('Markdown version:', markdown.version)

如何摆脱旧模块取决于一开始的安装方式。

避免此类冲突的首选方法是使用虚拟环境(或简称virtualenv)。

您链接到的教程使用虚拟环境,因此,如果逐步遵循它,就不会出现此问题。也许您只是忘了激活virtualenv?

Linux / Mac:source env/bin/activate

Windows:env\Scripts\activate

答案 1 :(得分:2)

我遇到同样的问题,但是poetry不允许我将Markdown 2.6.11 更新到 3 + ,因为{ {1}}取决于apache-airflow (1.10.10)

我成功使用了markdown (>=2.5.2,<3.0)中声明的解决方法:

settings.py

非常感谢redditer

答案 2 :(得分:1)

我发现此解决方案对我有用

pip install git+https://github.com/Python-Markdown/markdown.git

答案 3 :(得分:0)

这是因为我的项目正在导入的Markdown版本。 因为我的全球Markdown版本是3.1 但是当我在调试后在项目中检查它时,它仍然是版本2。

创建虚拟环境是解决此问题的方法。

谢谢。