Running extra scripts or processes is always needed when you have some new idea that works with web development and in Python!!! it is always.
It can be any script that may include a loading of data, processing, and cleaning of data, or any ML phase when making an application providing business logic directly in views or models is not always best. As django conventions refer to ‘thin views’, we must try to trim out the logic and try to embed it in some other files.
Django extensions in a package that enables you to run the extra scripts you need to install it using pip, use terminal and type
pip install django-extensions
add the django-extensions in installed apps found in setting.py file
INSTALLED_APPS = [ ... ... 'django_extensions', ]
Now create a folder named scripts in your project that will contain all the python files which you can execute
add an empty python file named ‘__init__.py’ this specifies that scripts in also part of Django projects
create new files that will contain the code that you need to execute, name anything you like
example: To load data from CSV files to the database before running the server
import csv from site.models import Destination def run(): # All data in run method only will be executed fhand = open('location.csv') reader = csv.reader(fhand) next(reader) for row in reader: latitude = row longitude = row name = row item = Destination.objects.create(name=name,latitude=latitude,longitude=longitude) item.save() print("Data Added")
Now to run the script simply fire the command as below where ‘load’ is a file name
python manage.py runscript load
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course