2

I have Django project. I need to add app to INSTALLED_APPS or change template config using another python script. What is the best way to do that?

I have several ideas.

  • Open settings.py as text file from Python and modify it. Seems to be wheel reinvention and opens box with many errors (escaping and so on).
  • Use Python modules like ast but it is pretty low level and more for read access (and I need to write data back).
  • Use some Django tools (I am not sure if such tool exists).

What is the best way to do that?

PS: Parse a .py file, read the AST, modify it, then write back the modified source code is related, but it is not Django specific and pretty old.

Community
  • 1
  • 1
user996142
  • 2,753
  • 3
  • 29
  • 48
  • There's a lot more involved than just adding to this, you would still need to reference it throughout your code and handle cases when it doesn't exist. Simply don't do it, if you need the app import it normally – Sayse Sep 16 '16 at 15:40

1 Answers1

2

A better (meaning more safe and clean) approach would be to generate a python module and then use it in settings.py. For example, have your script create a file with these contents:

ADDITIONAL_APPS = [
    'foo',
    'bar',
]

Save it as, say, additional_settings.py and put it in the same directory as settings.py, and then in settings.py add lines

from .additional_settings import ADDITIONAL_APPS

...

INSTALLED_APPS += ADDITIONAL_APPS

This way you don't have to parse anything at all and you don't risk ruining your existing settings.

Let me know if it works

Dunno
  • 3,632
  • 3
  • 28
  • 43