541๐
The <<
part is wrong, use <
instead:
$ ./manage.py shell < myscript.py
You could also do:
$ ./manage.py shell
...
>>> execfile('myscript.py')
For python3 you would need to use
>>> exec(open('myscript.py').read())
295๐
Youโre not recommended to do that from the shell
โ and this is intended as you shouldnโt really be executing random scripts from the django environment (but there are ways around this, see the other answers).
If this is a script that you will be running multiple times, itโs a good idea to set it up as a custom command ie
$ ./manage.py my_command
to do this create a file in a subdir of management
and commands
of your app
, ie
my_app/
__init__.py
models.py
management/
__init__.py
commands/
__init__.py
my_command.py
tests.py
views.py
and in this file define your custom command (ensuring that the name of the file is the name of the command you want to execute from ./manage.py
)
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, **options):
# now do the things that you want with your models here
- [Django]-How to add superuser in Django from fixture
- [Django]-Django Form File Field disappears on form error
- [Django]-Is there a way to filter a queryset in the django admin?
128๐
For anyone using Django 1.7+, it seems that simply import the settings module is not enough.
After some digging, I found this Stack Overflow answer: https://stackoverflow.com/a/23241093
You now need to:
import os, django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
django.setup()
# now your code can go here...
Without doing the above, I was getting a django.core.exceptions.AppRegistryNoReady
error.
My script file is in the same directory as my django project (ie. in the same folder as manage.py)
- [Django]-Set up a scheduled job?
- [Django]-How to format time in django-rest-framework's serializer?
- [Django]-The QuerySet value for an exact lookup must be limited to one result using slicing. Filter error
73๐
Iโm late for the party but I hope that my response will help someone:
You can do this in your Python script:
import sys, os
sys.path.append('/path/to/your/django/app')
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
from django.conf import settings
the rest of your stuff goes here โฆ.
- [Django]-Django/DRF โ 405 Method not allowed on DELETE operation
- [Django]-Django edit user profile
- [Django]-Django's Double Underscore
50๐
runscript
from django-extensions
python manage.py runscript scripty.py
A sample script.py
to test it out:
from django.contrib.auth.models import User
print(User.objects.values())
Mentioned at: http://django-extensions.readthedocs.io/en/latest/command_extensions.html and documented at:
python manage.py runscript --help
Tested on Django 1.9.6, django-extensions 1.6.7.
- [Django]-Altering one query parameter in a url (Django)
- [Django]-Sending HTML email in django
- [Django]-Access web server on VirtualBox/Vagrant machine from host browser?
16๐
If IPython is available (pip install ipython
) then ./manage.py shell
will automatically use itโs shell and then you can use the magic command %run
:
%run my_script.py
- [Django]-Rendering a value as text instead of field inside a Django Form
- [Django]-Convert Django Model object to dict with all of the fields intact
- [Django]-Django testing: Test the initial value of a form field
15๐
@AtulVarma provided a very useful comment under the not-working accepted answer:
echo 'import myscript' | python manage.py shell
- [Django]-Django 1.5 custom User model error. "Manager isn't available; User has been swapped"
- [Django]-Saving ModelForm error(User_Message could not be created because the data didn't validate)
- [Django]-Detect mobile, tablet or Desktop on Django
14๐
If you donโt have many commands in your script, use -c
/--command
:
manage.py shell --command "import django; print(django.__version__)"
- [Django]-Python 3 list(dictionary.keys()) raises error. What am I doing wrong?
- [Django]-Django-Forms with json fields
- [Django]-Why is __init__ module in django project loaded twice
10๐
Iโm late for the party but I hope that my response will help someone: You can do this in your Python script:
step1: Import
import mysite.asgi
step2: Need to execute a Python script simply typing:
python test.py
Where test.py file like look this:
import mysite.asgi
from polls.models import GMD_TABLE
print ( [obj.gt_GMD_name for obj in GMD_TABLE.objects.all()] )
FINALY: The result will be:
['ISHWARDI', 'JHENAIDHA', 'HVDC CIRCLE']
Where [โISHWARDIโ, โJHENAIDHAโ, โHVDC CIRCLEโ] is the values of GMD_TABLE
- [Django]-Django + Ajax
- [Django]-How do you Serialize the User model in Django Rest Framework
- [Django]-With DEBUG=False, how can I log django exceptions to a log file
8๐
You can just run the script with the DJANGO_SETTINGS_MODULE
environment variable set. Thatโs all it takes to set up Django-shell environment.
This works in Django >= 1.4
- [Django]-Remove pk field from django serialized objects
- [Django]-Django middleware difference between process_request and process_view
- [Django]-Paginate relationship in Django REST Framework?
6๐
As other answers indicate but donโt explicitly state, what you may actually need is not necessarily to execute your script from the Django shell, but to access your apps without using the Django shell.
This differs a lot Django version to Django version. If you do not find your solution on this thread, answers here โ
Django script to access model objects without using manage.py shell
โ or similar searches may help you.
I had to begin my_command.py with
import os,sys
sys.path.append('/path/to/myproject')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.file")
import django
django.setup()
import project.app.models
#do things with my models, yay
and then ran python3 my_command.py
(Django 2.0.2)
- [Django]-What is the difference between null=True and blank=True in Django?
- [Django]-How to get getting base_url in django template
- [Django]-Django.db.utils.IntegrityError: duplicate key value violates unique constraint "django_migrations_pkey"
5๐
You can simply run:
python manage.py shell < your_script.py
It should do the job!
- [Django]-Has Django served an excess of 100k daily visits?
- [Django]-Django 1.5 custom User model error. "Manager isn't available; User has been swapped"
- [Django]-Filtering dropdown values in django admin
3๐
Note, this method has been deprecated for more recent versions of django! (> 1.3)
An alternative answer, you could add this to the top of my_script.py
from django.core.management import setup_environ
import settings
setup_environ(settings)
and execute my_script.py
just with python in the directory where you have settings.py
but this is a bit hacky.
$ python my_script.py
- [Django]-Get user profile in django
- [Django]-Django Rest Framework Conditional Field on Serializer
- [Django]-Import data from excel spreadsheet to django model
3๐
import os, sys, django
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
sys.path.insert(0, os.getcwd())
django.setup()
- [Django]-Many-To-Many Fields View on Django Admin
- [Django]-What does error mean? : "Forbidden (Referer checking failed โ no Referer.):"
- [Django]-What is a django.utils.functional.__proxy__ object and what it helps with?
3๐
If you want to run in in BG even better:
nohup echo 'exec(open("my_script.py").read())' | python manage.py shell &
The output will be in nohup.out
- [Django]-VueJS + Django Channels
- [Django]-How do you detect a new instance of the model in Django's model.save()
- [Django]-Django testing: Test the initial value of a form field
1๐
came here with the same question as the OP, and I found my favourite answer precisely in the mistake within the question, which works also in Python 3:
./manage.py shell <<EOF
import my_script
my_script.main()
EOF
- [Django]-Sending an SMS to a Cellphone using Django
- [Django]-How to revert the last migration?
- [Django]-Get count of related model efficiently in Django
1๐
If you want to execute startup script (e.g. import some django models to work with them interactively) and remain in django shell:
PYTHONSTARTUP=my_script.py python manage.py shell
- [Django]-*_set attributes on Django Models
- [Django]-Django filter JSONField list of dicts
- [Django]-Django: How to check if the user left all fields blank (or to initial values)?
1๐
Actually it is very simple, once you open django shell with
python manage.py shell
then simply write import test
to import test.py
# test.py
def x():
print('hello');
Now you can execute the commands in this file as
test.x() // will print hello
- [Django]-Django middleware difference between process_request and process_view
- [Django]-How can I get MINIO access and secret key?
- [Django]-Django gunicorn sock file not created by wsgi
1๐
Add these lines to your python script.py
import os
import sys
import django
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
sys.path.append(str(BASE_DIR))
os.environ.setdefault("DJANGO_SETTINGS_MODULE","django_server_app.settings")
django.setup()
# add your code here
then go to the project directory and run python script.py
- [Django]-Malformed Packet: Django admin nested form can't submit, connection was reset
- [Django]-How about having a SingletonModel in Django?
- [Django]-Error: No module named staticfiles
0๐
Something I just found to be interesting is Django Scripts, which allows you to write scripts to be run with python manage.py runscript foobar. More detailed information on implementation and scructure can be found here, http://django-extensions.readthedocs.org/en/latest/index.html
- [Django]-Celery : Execute task after a specific time gap
- [Django]-Django AutoField with primary_key vs default pk
- [Django]-Django project models.py versus app models.py
0๐
django.setup() does not seem to work.
does not seem to be required either.
this alone worked.
import os, django, glob, sys, shelve
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myProject.settings")
- [Django]-Django โ No module named _sqlite3
- [Django]-How about having a SingletonModel in Django?
- [Django]-Get list item dynamically in django templates
0๐
Try this if you are using virtual enviroment :-
python manage.py shell
for using those command you must be inside virtual enviroment. for this use :-
workon vir_env_name
for example :-
dc@dc-comp-4:~/mysite$ workon jango
(jango)dc@dc-comp-4:~/mysite$ python manage.py shell
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>>
Note :- Here mysite is my website name and jango is my virtual enviroment name
- [Django]-Django.contrib.gis.db.backends.postgis vs django.db.backends.postgresql_psycopg2
- [Django]-How do I use an UpdateView to update a Django Model?
- [Django]-FileUploadParser doesn't get the file name
0๐
Other way itโs execute this one:
echo 'execfile("/path_to/myscript.py")' | python manage.py shell --settings=config.base
This is working on Python2.7 and Django1.9
- [Django]-Django: remove a filter condition from a queryset
- [Django]-Add additional options to Django form select widget
- [Django]-How to tell if a task has already been queued in django-celery?
0๐
The django shell is the good way to execute a python module with the django environment, but it is not always easy and tiresome to import modules and execute functions manually especially without auto-completion. To resolve this, I created a small shell script โrunscript.shโ that allows you to take full advantage of the auto-completion and the log history of the Linux console.
NB: Copy runscript.sh to the root project and set the execute right (chmod +x)
For example:
I want to run python function named show(a, b, c) in module do_somethings.py in myapp/do_folder/
The standard django way (manage.py shell):
python3 manage.py shell
> from myapp.do_folder import do_somethings
> do_somethings.show("p1", "p2" , 3.14159)
With script (runscript.sh):
./runscript.sh myapp/do_folder/do_somethings.py show p1 p2 3.14159
The script is not limited in number of arguments. However only arguments of primitive types are supported (int, float, string)
- [Django]-How do I do a not equal in Django queryset filtering?
- [Django]-Django create userprofile if does not exist
- [Django]-Is it bad to have my virtualenv directory inside my git repository?
0๐
Late to the party. But this might be helpful for someone.
All you need is your script and django-extensions
installed.
Just run the shell_plus
available in django_extensions
and import the script that youโve written.
If your script is scpt.py
and itโs inside a folder fol
you can run the script as follows.
python manage.py shell_plus
and just import your script inside the shell as follows.
>>> from fol import scpt
- [Django]-Naming convention for Django URL, templates, models and views
- [Django]-How to pass multiple values for a single URL parameter?
- [Django]-In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?
0๐
First check your file.
py manage.py
If your file is shown
[contracts]
category_load
Now you can run your .py file by typing in the powershell(terminal)
py manage.py category_load
- [Django]-Alowing 'fuzzy' translations in django pages?
- [Django]-How to loop over form field choices and display associated model instance fields
- [Django]-Django character set with MySQL weirdness
- [Django]-Django F() division โ How to avoid rounding off
- [Django]-With DEBUG=False, how can I log django exceptions to a log file
- [Django]-What's the difference between select_related and prefetch_related in Django ORM?