-->

Python: ImportError: cannot import name generic

By: Varghese Chacko 1 year, 6 months ago

After upgrading to django 1.9. Whenever I was executing the command ./manage.py runserver , I got the error :

Unhandled exception in thread started by <function wrapper at 0x10385b500>
Traceback (most recent call last):
  File "/Library/Python/2.7/site-packages/Django-1.9-py2.7.egg/django/utils/autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/Django-1.9-py2.7.egg/django/core/management/commands/runserver.py", line 109, in inner_run
    autoreload.raise_last_exception()
  File "/Library/Python/2.7/site-packages/Django-1.9-py2.7.egg/django/utils/autoreload.py", line 249, in raise_last_exception
    six.reraise(*_exception)
  File "/Library/Python/2.7/site-packages/Django-1.9-py2.7.egg/django/utils/autoreload.py", line 226, in wrapper
    fn(*args, **kwargs)
  File "/Library/Python/2.7/site-packages/Django-1.9-py2.7.egg/django/__init__.py", line 18, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Library/Python/2.7/site-packages/Django-1.9-py2.7.egg/django/apps/registry.py", line 108, in populate
    app_config.import_models(all_models)
  File "/Library/Python/2.7/site-packages/Django-1.9-py2.7.egg/django/apps/config.py", line 202, in import_models
    self.models_module = import_module(models_module_name)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module
    __import__(name)
  File "/Users/shakil_grofers/src/django-eav/eav/models.py", line 42, in <module>
    from django.contrib.contenttypes import generic

The reason for this error is generic has been deprecated in Django 1.7 and is no more in Django 1.9.  Instead of django.contrib.contenttypes.generic.GenericForeignKey we can now use django.contrib.contenttypes.fields.GenericForeignKey. See the sample code in the documentation:

from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType

class TaggedItem(models.Model):
    tag = models.SlugField()
    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    def __str__(self):              # __unicode__ on Python 2
        return self.tag

Wish to hire us?

We take the vision which comes from dreams and apply the magic of science and mathematics, adding the heritage of our profession and our knowledge to create a design.