How to run a series of manage.py commands in Django? - django

I have a Django project. Everytime I deploy, I need to run a series of manage.py command (such as syncdb, south migiration, fixture update).
I am getting tired of type the command line by line and therefore I wrote a python script to do these:
import subprocess
subprocess.call(['python', 'manage.py', 'syncdb'])
#Skip the detail
subprocess.call(['python', 'manage.py', 'loaddata', 'setup/fixture.xml'])
I am wondering if there is a better way to do this?
Thanks.

You can use fabric, a Python library that allows you to script remote actions. This question has some links in the accepted answer for more information on fabric and django.
You can also call management commands directly:
from django.core.management import call_command
call_command('syncdb')
call_command('loaddata', 'setup/fixture.xml')
Save that as a normal python file and execute it from your shell or as part of your deployment scripts.

Related

How I can run a telegram bot with the Django project?

Now, to run the bot through Django, I first use the python manage.py runserver command and then follow the link to launch a view with my bot. Can you tell me if there is an easier way to start my bot automatically when starting a Django project?
Actually, you can use a management command to run your bot with something like
python manage.py runbot
All Django context, including DB and settings, will be available
Reference to management command page:
https://simpleisbetterthancomplex.com/tutorial/2018/08/27/how-to-create-custom-django-management-commands.html
Maybe is a little late but you can do the following:
create the bot.py file in the same folder where manage.py is.
inside the bot.py make sure you import the following:
import django
import os
os.environ['DJANGO_SETTINGS_MODULE'] = '{Folder where your settings are}.settings'
django.setup()
and in order to run you just type python bot.py

Run a python script just after run server django

I have a python script with indefinite loop it keeps in checking for the data, now I am confused how do I execute it so that it keeps running if the server is running.
I think the script should run just after I run server in django but how do I run this script?
Any suggestions?
django-admin runserver is only for development use. Assuming this is a development environment, probably simplest to just run your script in a separate console, or make a simple shell script that starts the django server, backgrounds that process, then runs your script.
#!/bin/sh
django-admin runserver &
/path/to/my/script.py &
You'll need to kill those processes manually before re-running that script.
In a production environment, use WSGI to run Django and something like supervisord to run the other script. You could configure the OS init system (probably systemd) to ensure both of these tasks start on reboot and remain running.
The first big part is to pack your indefinite loop into a function, and use huey/celery/etc to make it a 'task' that runs asynchronously.Then, call this task to run in your views.py/models.py/manage.py.
HOW TO LET THE TASK RUN ASYNCLY:
HUEY:[https://huey.readthedocs.io/en/latest/]
HOW TO RUN THE TASK WHEN YOU START THE SERVER (2 ways):
Edit your manage.py ,add your function call at the line right behind the import of manage.py.
#!/usr/bin/env python
import os
import sys
print('Interesting things happens.') # THIS IS WHERE YOU RUN YOUR tasks.checkdata.
if __name__ == '__main__':
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'OTAKU.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
However , maybe you want to leave the manage.py alone. Create a new app in your project, with views.py and models.py.(Remember to add this app to your INSTALLED_APPS in settings.py)
In views.py :
print("The view is loading.")# THIS IS WHERE YOU CAN RUN YOUR tasks.checkdata.
In models.py:
print("The models is loading.")# THIS IS WHERE YOU CAN RUN YOUR tasks.checkdata.
And when you run your server now, this is what you might see:
Interesting things happens.
The models is loading.
Interesting things happens.
The models is loading.
Performing system checks...
The view is preparing itself.
System check identified no issues (0 silenced).
July 15, 2019 - 11:52:03
Django version 2.1.3, using settings 'rayos.settings'
Starting development server at http://0.0.0.0:9988/
Quit the server with CONTROL-C.
Replace the print part of the script with your data checking functions and it will work.

How can i use django's runscript?

I am trying to run a script using django's runscript. I followed everything in the documentation. Did i miss something?
But when i tried running it from the command line. it says unknown command 'runscript'
(env) C:\Users\MIS\hr system\hr_project>python manage.py runscript automail.py
Unknown command: 'runscript'
You need to install django-extensions if you want the runscript command. If you don't want to do that, you can:
Run your script directly. Keep in mind that you need to specify the Django settings module as such:
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")
from your_project.models import SomeModel
# Your code goes here...
Make a custom manage.py command. You can use the official how-to: https://docs.djangoproject.com/en/2.2/howto/custom-management-commands/

how to execute the interactive commands programmatically in django-tenants

in my terminal i can execute
1)first command
python manage.py tenant_command rebuild_index
2)second command.
the terminal will ask which schema shall i execute. for that i enter my schema name called xxx
Enter Tenant Schema ('?' to list schemas): xxx
3)3rd command i need to enter y/n option extra in terminal
then i Entered Enter
This is working fine so how to achieve this in pragmatically using management call_command pragmatically in django
management.call_command('python manage.py tenant_command rebuild_index', 'xxx')
but it giving error like
File "/home/hi/venv/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 94, in call_command
raise CommandError("Unknown command: %r" % name)
CommandError: Unknown command: 'python manage.py tenant_command rebuild_index'
so please any body tell me is it possible to achieve this kind of interactive terminal commands to run pragmatically in django
You need to pass the schema name as a keyword argument called schema_name so that the tenant_command does not prompt. You also do not need to pass python manage.py.
The syntax you want is:
from django.core import management
management.call_command('tenant_command', 'rebuild_index', schema_name='xxx')
The function call_command only needs the command name, like this:
management.call_command('tenant_command', 'rebuild_index')
Try that and see if that works. Read the docs I linked as well, there are a few examples.
I solved my problem by running it in a periodic task instead of running manual rebuild index commands everytime. See code below...
from django.core import management
def hi():
management.call_command('rebuild_index',schema_name="xxx",interactive=False)

Import all modules in django

In django is there way to import all modules
ex: from project.models import *
ex: from project1.models import *
Can this be done with one statement
If you just want to do this when testing things in the shell, look into the shell_plus command provided by the django-extensions project.
This is a really neat extension, which starts a shell and automatically loads all the models in your project when you do ./manage.py shell_plus from the command line.