Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AttributeError at / 'OrderedDict' object has no attribute 'register' in Django REST framework from quickstart documentation

I am trying to work with Django REST framework but I am getting the AttributeError at / 'OrderedDict' object has no attribute 'register'. I think I have followed the documentation properly Can someone help with this.

Link to the tutorial: https://www.django-rest-framework.org/tutorial/quickstart/

I have already used Django now I am trying to work with the Django REST framework but following the quickstart tutorial is resulting in: AttributeError at / 'OrderedDict' object has no attribute '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'
    ]
}

The error response is :

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'

The result should be : https://www.django-rest-framework.org/img/quickstart.png

like image 915
saibhaskar Avatar asked Aug 13 '19 14:08

saibhaskar


3 Answers

I found this solution works for me

pip install git+https://github.com/Python-Markdown/markdown.git
like image 98
Ayoub EL MAJJODI Avatar answered Nov 20 '22 14:11

Ayoub EL MAJJODI


The version of the markdown library you have installed is incompatible with the version of Django REST Framework you are using.

Update the markdown library to at least 3.0 to fix this issue.

Edit: As mentioned in the comments, if you have markdown 3.1 installed, your Python interpreter probably picks up an older version that is installed somewhere else.

You can check which version of markdown your interpreter picks up, by importing it and inspecting markdown.__file__ and markdown.version.

The most reliable way is probably to add these lines to your settings.py:

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

How to get rid of the old module depends on how it got installed in the first place.

The preferred way to avoid these kinds of conflicts is using a virtual environment (or short virtualenv).

The tutorial you linked to uses a virtual environment, so if you followed it step by step, you should not have this problem. Maybe you simply forgot to activate the virtualenv?

Linux/Mac: source env/bin/activate

Windows: env\Scripts\activate

like image 34
Daniel Hepper Avatar answered Nov 20 '22 15:11

Daniel Hepper


I have the same issue, but poetry does not allow me to update Markdown to from 2.6.11 to 3+ because apache-airflow (1.10.10) depends on markdown (>=2.5.2,<3.0)

I successfully used this workaround declared in settings.py:

from rest_framework import compat
compat.md_filter_add_syntax_highlight = lambda md: False

Thanks a lot to this redditer

like image 2
Артемий Быков Avatar answered Nov 20 '22 16:11

Артемий Быков