Modify Django settings programmatically
<p>I have Django project. I need to add app to <code>INSTALLED_APPS</code> or change template config using another python script. What is the best way to do that?</p>

<p>I have several ideas.</p>

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

<p>What is the best way to do that?</p>

<p>PS: <a href="http://stackoverflow.com/questions/768634/parse-a-py-file-read-the-ast-modify-it-then-write-back-the-modified-source-c">Parse a .py file, read the AST, modify it, then write back the modified source code</a> is related, but it is not Django specific and pretty old. </p>

<p>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:</p>

<pre><code>ADDITIONAL_APPS = [
    'foo',
    'bar',
]
</code></pre>

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

<pre><code>from .additional_settings import ADDITIONAL_APPS

...

INSTALLED_APPS += ADDITIONAL_APPS
</code></pre>

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

<p>Let me know if it works</p>

python django