In this Python Django tutorial, we will learn about the import functions in Django and will discuss in brief their uses and functionality in a Python Django project.
What is import functions?
Importing a function means we have already created a function in a file of our project and we want to import that function and its functionalities in another file within that project. Django allows easy transfer of functions and models with the import function.
How to import a function in Django?
To understand how import works in Django we will create files and import functions from one file to another. So, let’s go to an example now.
We have created a file name views.py and below is the code of the views.py file.
from django.htttp import httpResponse def contact(request): return HttpResponse("<h1>Contact Page</h1>")
We have created a function Contact which will return the text “Contact Page” rendered by HTML tags. Now create a urls.py file in the same folder and import the function Contact in urls.py. Below is the code for the urls.py file.
from django.conf.urls import url, include from .views import contact urlpatterns = [ url(' ', contact, name='conatct'), ]
In the urls.py file, we have written from .views import contact with this line, we have imported the contact function from the views.py file to urls.py within the same folder. So, this is how the import function works in Python Django.
Let’s see another example where we will import the inbuilt module in our file and use their functionalities. For this create a file imp1.py and follow the below code.
from math import sqrt,pi result = sqrt(9) * pi print(result)
We have used the math module which is a built-in module in the Python 3 standard library that provides standard mathematical constants and functions. When you will run this code you will get the output as shown in the below picture.
In this Python Django tutorial, we learned about the use and implementation of import functions in Python. With the above two examples, we came to understand how to import functions within a folder and how to import built-in modules in our Python file.
You may also like:
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.