Prometheus Prometheus - 2 months ago 23
Python Question

Django 1.9 how to import in __init__.py

I've updated from Django 1.8 to 1.9.

apps/comment/__init__.py (in 1.8)

from .models import Mixin


In Django 1.9 this no longer works but I still want to import
Mixin
in the same way.

So I tried this:

apps/comment/__init__.py

default_app_config = 'comment.apps.CommentConfig'


apps/comment/apps.py

# Django imports.
from django.apps import AppConfig


class CommentConfig(AppConfig):
name = 'comments'

def ready(self):
"""
Perform initialization tasks.
"""
from .models import CommentMixin


This however, does not appear to work, i.e. I cannot do
from comment import Mixin
, why?

Answer

Adding from .models import CommentMixin imports CommentMixin so that you can use it inside the ready() method. It does not magically add it to the comment module so that you can access it as comments.CommentMixin

You could assign it to the comments module in the ready() method.

# Django imports.
from django.apps import AppConfig
import comments

class CommentConfig(AppConfig):
    name = 'comments'

    def ready(self):
        """
        Perform initialization tasks.
        """
        from .models import CommentMixin
        comments.CommentMixin = CommentsMixin

However I would discourage you from doing this, you might end up with hard-to-debug import errors later on. I would just change your imports to from comment.models import CommentMixin.