Django Rest Framework with South solve for “cannot import name migrations”

Disclaimer: This isn’t a Django Rest Framework guide/tutorial post.

Today, I decided to give Django Rest Framework a go. Since this while I have been using Tastypie for developing APIs, and it has been pretty good with me. I like it because it is well documented and over time I have become quite familiar with the framework.

For my current project, I use Django 1.4 with South 0.7.6 for database migrations. I had to use Django Rest Framework 3.1.3 which is the last version that supports Django 1.4 and also it had support for TokenAuthentication which was required by my project.

Django versions < 1.7 used South for database migrations. Later on from Django 1.7, migrations were moved into Django project itself hence you do not need to use South anymore.

I installed DRF like so:

pip install djangorestframework==3.1.3

There are different authentication methods used to authenticate a client/user. I needed to use TokenAuthentication which verifies the client against a token/key which is stored on to the Database. To configure your project to be able to use TokenAuthentication, please refer the official documentation. You will need to add ‘rest_framework.authtoken’ under INSTALLED_APPS in settings.py.

The token for each user is created under table authtoken_token in MySQL. To be able to migrate these changes you will need to run south migrations:

python manage.py schemamigration <app_name> --auto
python manage.py migrate <app_name>

However Django throws an error like so:

from django.db import models, migrations
ImportError: cannot import name migrations

This does not mean DRF version 3.1.3 does not support South. If you look inside /site-packages/rest_framework/authtoken/ there are 2 folders 1) Migrations 2) South Migrations. The error occurs because DRF assumes you are using Django’s builtin migrate command to make database migrations. We need to override this behaviour. To do this simply rename the “southmigrations” folder to “migrations” and do away with the original migrations folder. :)

I hope this solution worked for you, though I think the best thing to do would be to upgrade your Django version.

Advertisements
This entry was posted in Django, Experience and tagged , , , . Bookmark the permalink.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s