Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override Django apps.py and its AppConfig for third-party apps which is not there?

Tags:

python

django

Since Django 1.7 the AppConfig feature has been added suggesting that post_migrate signals should be put in the ready() part of its customized implementation - https://docs.djangoproject.com/en/stable/ref/signals/#post-migrate

The basic way to implement AppConfig described by the docs is to point to it in the __init__.py file using default_app_config setting. The docs would also suggest a way to override an existing AppConfig for any app: https://docs.djangoproject.com/en/stable/ref/applications/#for-application-users

I have researched a bit and found out that django actually creates AppConfig instance for every app in INSTALLED_APPS even if its custom implementation is not implemented it would bootstrap the default for you.

My question is how one should provide a customized app configuration with post_migrate signal for an app that doesn't implement AppConfig (the easiest example would be a third party package without apps.py)?

I know that even for this app the django would go and create a default version of AppConfig but where and how should i tell it NOT to do so and use my custom AppConfig instead with overrided ready() method implementation to add post_migrate?

like image 227
canufeel Avatar asked Jan 06 '23 04:01

canufeel


1 Answers

Let us suppose for a moment that you wished to create a custom AppConfig for django crispy_forms (which you have installed into your virtualenv).

Step 1: Create a folder named crispy_forms in your project. Step 2: Create an __init__.py in that folder and paste the following

from django.apps import AppConfig

default_app_config = 'crispy_forms.apps.MyAppConfig'

step 3: Create an apps.py in crispy_forms folder and paste

from django.apps import AppConfig

class MyAppConfig(AppConfig):

    verbose_name = 'customized crispy_forms'
    name = "crispy_forms"

    def __init__(self, app_name, app_module):
        AppConfig.__init__(self,app_name, app_module)
        print 'My app config', app_name, app_module

If django doesn't reload classes, restart the development server and then you will see something like:

My app config crispy_forms <module 'crispy_forms' from '/home/xxx/project/crispy_forms/__init__.pyc'>
like image 73
e4c5 Avatar answered Jan 29 '23 05:01

e4c5