6

I have a simple python file that I eventually want to run from chron.

It looks like this:

from customers.models import Customer, NotificationLogEntry


def hello():
    customers =  Customer.objects.all()
    for c in customers:
        log_entry = NotificationLogEntry(
                                          customer=c,
                                          sent=True,
                                          notification_type=0,
                                          notification_media_type=0,
                                          )
        log_entry.save()


if __name__ == '__main__':
    hello()

When I run this with:

python notifications.py

I get an import error:

Traceback (most recent call last):
  File "notifications.py", line 1, in <module>
    from customers.models import Customer, NotificationLogEntry
ImportError: No module named customers.models

This module exists and I call it without any problem within my django app. Why am I getting this error outside of my app?

4 Answers 4

10

You can create a custom command

https://docs.djangoproject.com/en/dev/howto/custom-management-commands/

Or, run ./manage.py shell then import your file

Or, load the django settings

http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/

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

Comments

6

Here's super simple option if you're running cron jobs:

cat run.py | ./manage.py shell

1 Comment

If you have the django-extensions package installed you can use the ./manage.py runscript command. django-extensions.readthedocs.io/en/latest/runscript.html
3

you need to set up project path

import os

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")

# your imports, e.g. Django models
from customers.models import Customer, NotificationLogEntry

1 Comment

Great answer, works perfectly with Python2 and Django1.7 for running python scripts to interact with Django from the command line.
0

From https://docs.djangoproject.com/en/1.11/releases/1.7/ we see:

Standalone scripts

If you’re using Django in a plain Python script — rather than a management command — and you rely on the DJANGO_SETTINGS_MODULE environment variable, you must now explicitly initialize Django at the beginning of your script with:

import django

django.setup()

This worked for me perfectly. YMMV.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.