Skip to content
Related Articles

Related Articles

Improve Article
Running Extra scripts in Django
  • Last Updated : 16 Mar, 2021

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

load.py

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[0]
        longitude = row[1]
        name = row[2]
        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

My Personal Notes arrow_drop_up
Recommended Articles
Page :