Upgrading to Django 2.x

If you work with Django 1.11.x before, and want to upgrade your project to Django to 2.x version, you maybe like me, encounter some of following errors. This article previously posted in Some errors encounter in Django 2.x Projects. Without further ado, here some errors that I encountered when upgrading my Django version to 2.x:

ImportError: No module named 'django.core.urlresolvers'

If you tried to import reverse from django.core.urlresolvers. you will got those error. This is because Django 2.x removes the django.core.urlresolvers module, which was moved to django.urls in version 1.10. We need to make some changes before our code works. You should change any import to use django.urls instead

from django.urls import reverse
                    

'WSGIRequest' object has no attribute 'user' Django admin

In Django 1.11.x we are using MIDDLEWARE_CLASSES in our settings.

MIDDLEWARE_CLASSES = (
    'django.middleware.security.SecurityMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ...
)
                    

The new-style for Django 2.x is MIDDLEWARE (introduced in Django 1.10) .

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

'djdt' is not a registered namespace

This is not exactly Django 2.x problem, but because of django-debug-toolbar. Just add debug_toolbar.middleware.DebugToolbarMiddleware in MIDDLEWARE, and add urlpattern:

if DEBUG:
 import debug_toolbar
 urlpatterns += [
  url(r'^__debug__/', include(debug_toolbar.urls)),
  ...
 ]
                    

But before upgrading to the latest version of Django, please make sure that you are using Python 3.x (In my case, 3.7.x). If not, this is the first thing that you need to upgrade, as the Python 2.x support was dropped.