How to Import a Function in Django


In this article, we go over how to import a function in Django.

What we mean by import a function is that we create a function in one page of our project directory and then we import function into another page, so that that function can be used on another page.

Django allows for easy transports of functions, pages, data, etc, from one page to another pretty easily.

So, for example, we can import a function from the file into the file.

So, this is what is meant by importing a function. We can then use a function from one page on another page in the project directory.

So, let's go over an example now.

We will create a function in the file and import it into the file. File

So, we'll create a function homepage in the file. It will return "Home Page"

The code for this is shown below.

So, we've now created a function called home that returns "Home Page" rendered by HTML h1 header tags.

Now, let's go to the file in the same folder. File

So, we will now import the function that we created into the file.

Below is the file.

So, with the line, from .views import home, we import from the views. py file the home function. The . means that it's within the same folder.

So, from within the same folder, we import the home function from the file.

If you don't want to put . and instead want to put the folder name, the above file can be rewritten as the following, shown below.

The that we are dealing with is homepage.

So, say, we have in the homepage directory, in the file, the home function.

The line, from homepage.views import home, imports the home function from the file in the homepage directory.

So, now let's consider the last option.

Let's say we want to import a function from another app in the app we're working with.

So, let's say we're working in the homepage directory, yet we want to import a function from another app, let's say, Blog app.

How do we do this?

The same thing. We specify the App name, followed by a ., followed by the name of the file we are importing the function from, followed by the import keyword, followed by the function.

So, for example, if we want to import a function from the Blog App into the homepage App, then we can have the following code.

Let's say the function is called, dothis.

So now we've imported the dothis function from the Blog App into the homepage App.

So, this is how we can import functions or any type of data in Django.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...