Is there a recommended approach for handling AppConfig when designing an app for Django 1.6 and 1.7?

748 Views Asked by At

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?

2

There are 2 best solutions below

1
inejc On BEST ANSWER

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'
0
lehins On

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