Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to run a django python file from command line

Tags:

python

django

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?

like image 754
Atma Avatar asked Sep 02 '14 01:09

Atma


1 Answers

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/

like image 52
James Lin Avatar answered Oct 11 '22 15:10

James Lin