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.

1
  • 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 Commented Sep 16, 2016 at 15:40

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.