You might occasionally need to run Python script in a Django project or shell when you have a new way that works with web development and Python. There are various approaches to doing this. In this post, we’ll examine the various Django methods for running Python scripts. Also, I have covered these points: –
- How to run Python Script in Django Project using shell
- How to run Python Script in Django using execfile
- How to run Python Script in Django using extension package
Run Python Script in Django Project using shell
Let’s first understand what is Python Script.
A Python file meant to be executed immediately is referred to as a script. When you run it, it should act immediately. As a result, scripts frequently have code that was written outside the parameters of any classes or functions.
Run Python Script and Manage File are located in the same folder
Now, let’s learn to run Python Script in Django Project using the shell.
- Firstly, create a project in Django (named “MyProject”) using the below-given command.
django-admin startproject MyProject
- Now, create a python file (named “sample.py”) in the same folder in which the manage.py file of the Django project is located.
# Program to add two numbers
# Define number
num1 = 15
num2 = 26
# Add number
result = num1 + num2
# Print result
print('Sum of the two number:', result)
Here, we define num1 and num2 two variables having integer-type values. Next, we define the result variable that will add the num1 and num2 using the + operator. At last, the print() function is called to print the sum of the two numbers.
- Navigate to the Django project’s root folder, where the manage.py file is located.
- Type the below-given command to run the Python Script “sample.py” in the Django project using the shell.
manage.py shell < sample.py
This is how you run Python Script in Django Project using shell when Python Script and Manage File are located in the same folder.
Read: Python list append Django
Run Python Script and Manage File located in different folders
Now, let’s learn to run Python Script in Django Project using the shell.
- Firstly, create a project in Django (named “MyProject”) using the below-given command.
django-admin startproject MyProject
- Now, create a python file (named “xyz.py”) in any other location.
# Program to multiple two numbers
# Define number
num1 = 23
num2 = 5
# Multiply number
result = 23 * 5
# Print result
print('Product of two number:'. result)
Here, we define num1 and num2 two variables having integer-type values. Next, we define the result variable that will multiply the num1 and num2 using the * operator. At last, the print() function is called to print the product of the two numbers.
- Navigate to the Django project’s root folder, where the manage.py file is located.
- Type the below-given command to run the Python Script “xyz.py” in the Django project using the shell.
manage.py shell < C:\Users\PythonGuides\Desktop\xyz.py
This is how you run Python Script in Django Project using shell when Python Script and Manage File are not located in the same folder.
Read: Python Django concatenate string
Run Python Script in Django using execfile
Let’s first understand what is execfile.
The execfile or exec is a python method that evaluates the contents of a file.
Now, let’s learn to run Python Script in Django Project using execfile.
- First, use the command below to create a project in Django with the name “MyProject”.
django-admin startproject MyProject
- Now, create a python file (named “abc.py”) in any location of your choice.
# Python program to swap two variables
# To take inputs from the user
a = input('Enter value of x: ')
b = input('Enter value of y: ')
# create a temporary variable and swap the values
temp = a
a = b
b = temp
# Print the result
print('The value of a after swapping: {}'.format(a))
print('The value of b after swapping: {}'.format(b))
Here, we define two variables called a and b that accept user input via the input() method. The value of the first variable, a, is then stored in the temporary variable temp.
The value of the second variable, b, is then assigned to variable a. Finally, by assigning variable b with the temporary variable temp for the given value, we finish this process of exchanging the value between two variables.
The swapped values are finally printed using the print() method.
- Navigate to the Django project’s root folder, where the manage.py file is located.
- Now, log into the Django shell by typing the below-given command.
manage.py shell
- Type the below-given command to run the Python Script “abc.py” in the Django project using execfile.
exec(open(''C:/Users/PythonGuides/Desktop/abc.py'').read())
This is how you run Python Script in Django Project using exec when Python Script and Manage File are located in any location.
Read: Python Django MySQL CRUD
How to run Python Script in Django using extension package
Sometimes you have a new idea for web development, but we are not assured about that. That new idea can be any script including data loading, processing, and cleaning.
So, the ideal way to implement business logic is not usually to put it directly in views or models. At that moment, you can install Django extensions as a package that allows you to run the additional scripts.
Now, let’s learn to run Python Script in Django Project using an extension package.
- As you know that Django extensions are a package that allows you to run additional scripts. You have to install it first by using a pip. Open a terminal window and type.
pip install django-extensions
- Create a Django project “Course”, by typing the below-given command in the terminal.
django-admin startproject Course
- Create a Django app “Register”, within the Django project, by typing the below command in the terminal.
python manage.py startapp Register
- Add the “djnago-extensions” package and “Register” app in the installed app list located in the settings.py file.
- By default, Django has a urls.py file under the project. Django recommends mapping the newly created app “Register” inside it.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path("admin/", admin.site.urls),
path('', include('Register.urls'))
]
- Create the Django models that define the fields and behaviors of the “Register” application data that we will be storing. Open the models.py file in the Django app and add the code below.
from django.db import models
# Create your models here.
class CourseRegister(models.Model):
title = models.CharField(max_length = 500)
author = models.CharField(max_length=200)
def __str__(self):
return self.author
Here, we create the model class “CourseRegister” which has the following database fields.
- title: The title of the blog post.
- author: The person who has written the post.
And to change the display name of the object in the Django model use def __str__(self). It will render the author name as we return the self.author.
- To register a model “CourseRegister” with the admin site, open the admin.py file and add the below-given code.
# Register your models here.
from django.contrib import admin
from .models import CourseRegister
admin.site.register(CourseRegister)
- To map the views, create an urls.py file under the app directory and add the below-given code inside it.
from django.urls import path
from Register import views
urlpatterns = [
path('', views.home, name='home'),
]
- The views are Python functions or classes that receive a web request and return a web response. Add the below-given code in the views.py file inside the app directory.
from django.shortcuts import render
# Create your views here.
def home():
print('Hello')
- To create a migration for the model, use the below-given command. Inside the migration folder, a migration file will be created.
python manage.py makemigrations
- Create a migration and then migrate it to reflect the database. Below is the migrate command.
python manage.py migrate
- To create the super user type the following command in the terminal.
python manage.py createsuperuser
- To add the records in the “CourseRegister” model open the admin application and add it.
- Create a scripts folder in the project directory to add the extra Python script.
- Create __init__.py file in the scripts folder to indicate that scripts are also part of the Django project.
- Create a new file “sample.py” that will contain the code that you need to execute. Add the below-given code in it.
from Register.models import CourseRegister
def run():
result = CourseRegister.objects.all()
print(result)
To get all the objects from the CourseRegister model before running the server we create this extra script having a function run.
- Now, run the script sample by typing the below-given command.
python manage.py runscript sample
This is how you run Python Script in Django using the extension package.
You may also like to read the following Python Django tutorials.
- Union operation on models Django
- Login system in Python Django
- Python Django random number
- Python Change Django Version
Conclusion
In this article, we have learned three distinct approaches to running Python scripts from Django. Additionally, we have also covered the following topics.
- How to run Python Script in Django Project using shell
- How to run Python Script in Django using execfile
- How to run Python Script in Django using extension package
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.