[Django]-Django settings for standalone

1👍

Someone upvoted this question today, which was nice, and I thought I’d come back to it with the benefit of hindsight, because the answers above didn’t help me. This is largely because I couldn’t adequately explain what I was trying to do; thanks to those who tried to help me.

For other noobs coming to it, there were two problems.

The first was – I was trying to run this from the command line in the first instance (not stated in the question, so partly my fault.) I wanted to run it from CLI to test it while I was building. Eventually, I wrote it into the views.py` as a an admin page, so I could trigger it whenever I needed it.

THe answer is, in fact, ‘make sure your file is on the Python path/inside your Django app’ If you’re coming to this new and want to run stuff from the command line, the now super-obvious-steps are:

If your structure is

/myproject 
    /app 
    /myproject

Save this as a defined function in a module (i.e. csvimportdoofer.py). Let’s call the function ‘foobar’.

cd into your Django project folder (the top level /myproject, where manage.py lives)

python manage.py shell

from app.csvimportdoofer import foobar

Now from the commandline I can just call foobar() whenever I want.

Honestly – the need to have the app.csvimportdoofer segment really threw me for ages, but mostly because I hadn’t worked with my own modules in python before coming to Django. Run before you can walk…

4👍

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'yoursite.settings'
import django
django.setup()

Then you can use your models.

from my_app.models import MyModel
all_objects = MyModel.objects.all()
👤eliasj

0👍

import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings'

Leave a comment