How to execute external script in the Django environment
Solution 1
I would say creating a new Custom management command is the best way to achieve this goal.
But you can run your script in a django environment. I use this sometimes to run a oneoff script or some simple tests.
You have to set the environment variable DJANGO_SETTINGS_MODULE
to your settings module and then you have to call django.setup()
I copied these lines from the manage.py
script, you have to set the correct settings module!
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.local")
django.setup()
Here is a simple template script which I use sometimes:
# -*- coding: utf-8 -*-
import os
import django
# you have to set the correct path to you settings module
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings.local")
django.setup()
from project.apps.bla.models import MyModel
def run():
# do the work
m = MyModel.objects.get(pk=1)
if __name__ == '__main__':
run()
It is important to note that all project imports must be placed after calling django.setup()
.
Solution 2
Many times you need scripts to play with db or more. But you need to the the django way i.e. the ORM and play with every thing that your project has.
You can checkout https://github.com/django-extensions/django-extensions
You create a scripts folder in your project home and write down a method run . the app provide you a way to run those scripts easily. How to do it.
Step 1 - Install the package. Step 2 - Create a scripts folder with init.py in project root, and add 'django_extensions' in your applications Step 3- Create a file send_email_to_users.py in scripts folder. Simple Example.
from project.models import MyModel
from django.contrib.auth.models import User
from project.utils import send_email
def run():
results = MyModel.objects.all()
for res in results:
send_mail(res.email)
Now from command line you can run
python manage.py runscript send_mail_to_users
Solution 3
If its just a one off script,
import django
django.setup()
from myapp.models.import MyModel
You need to have your environmental variable set up, so its easiest to run it from the IDE (make it part of the same project, right click on teh file and there should be a run option).
If you are looking for something to run on a production environment I would create a management command as suggested by DanEEStar.
![dabadaba](https://i.stack.imgur.com/evP8V.png?s=256&g=1)
dabadaba
Updated on June 08, 2022Comments
-
dabadaba about 2 years
I am trying to execute an external snippet for debugging and terminal-like purposes in the environment the Django console uses so it can connect to the db, etc.
Basically, I am just using it for the same reason one would fiddle with the console but I am using longer snippets to output some formatted information so it is handy to have that code in an actual file manipulated with an IDE.
An answer said you could do that by executing
python manage.py shell < snippet.py
but I did not see a successfull result. And although no errors are reported, I am not getting the excepted output, but only a series of>>>
prompts.So how can I do this?
By the way, I am using PyCharm, in case this IDE has a shorthand way of doing this or any special tool.
-
Daniel Roseman over 7 years
-
dabadaba over 7 yearsThanks for that. Although it seems I am having environment issues since an import is failing. If I understand right, I am to place ' management/commands` under any of the app directories where I may use the command, right?
-
bruno desthuilliers over 7 yearsYou have to put it in a
management/commands
sub-package of one of your (installed) apps (preferably one that the command relates to <g>). IOWyourapp/management
andyourapp/management/commands
must contain an__init__.py
file (usually empty).
-
-
dabadaba over 7 yearsI am getting the same import errors I was getting when trying to define a custom command :/ The modules failing to be imported are just modules from my own apps, but I just cannot figure out why they would fail when trying to do this, when no issues whatsoever happen when running the server or the terminal. What would even be different in this scenario so as to cause this sudden import error?
-
dabadaba over 7 yearsCan you give an example? I don't see how I may do this and what
django-extensions
has to do with it. -
DanEEStar over 7 yearsCan you show an example of a specific import from one of your models that fails.
-
kevr over 6 yearsThis does not work with Django on Python3 in Windows at the moment. It always complains about
DJANGO_SETTINGS_MODULE
not being set if I run it like this; if I pass in that environment variable on the command line instead it gives me ModuleNotFoundError for my project.settings