8

Django 1.7 has introduced a new way for handling application configuration that is independent of models.py. However the method for using the new AppConfig requires this line:

from django.apps import AppConfig

Unfortunately, this will break in Django 1.6 as there is no apps module.

Is it possible to have an app be compatible with 1.6 and 1.7 using conditional imports, or is it a matter of split code bases? If so, are is there a recommend guide, preferably from the Django developers on how to do so?

  • I don't know if you'll get an official guide or recommendation, but have you tried, maybe, simply adding the `apps` module from 1.7 to your Django 1.6 project and trying to manually integrate it? I'm sure there'll be some rough edges, but it's still a recent addition, so it can't break things up too much. Also, it only has like, [two files](https://github.com/django/django/tree/master/django/apps), so it can't be *a lot* of work, can it? – yuvi Feb 05 '15 at 00:32

2 Answers2

9

I am not sure about officially django suggested way, but that is how I would do it:

# myapp/apps.py

try:
    from django.apps import AppConfig
except ImportError:
    AppConfig = object

class MyAppConfig(AppConfig):
    # put all the necessary stuff for AppConfig

# myapp/__init__.py

default_app_config = 'myapp.apps.MyAppConfig'

This way if it's django>=1.7 it will use this MyAppConfig, otherwise myapp/apps.py module will be simply ignored, and it will work the same as before for django<1.7

lehins
  • 9,642
  • 2
  • 35
  • 49
4

How about using AppConfig only if django version >= 1.7 (take that into account in __ init __.py file too):

# myapp/apps.py
from django import VERSION as DJANGO_VERSION
if DJANGO_VERSION >= (1, 7):
    from django.apps import AppConfig
    class MyAppConfig(AppConfig):
        ...

# myapp/__init__.py
from django import VERSION as DJANGO_VERSION
if DJANGO_VERSION >= (1, 7):
    default_app_config = 'myapp.apps.MyAppConfig'
inejc
  • 550
  • 3
  • 14
  • I gave this a shot and it seems to work ok. I chose it because I prefer explicit checks to exceptions. –  Feb 12 '15 at 02:51