How to Import a Function in Django



Python


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 views.py file into the urls.py 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 views.py file and import it into the urls.py file.

views.py File

So, we'll create a function homepage in the views.py 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 urls.py file in the same folder.


urls.py File

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

Below is the urls.py 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 views.py file.

If you don't want to put . and instead want to put the folder name, the above urls.py 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 views.py file, the home function.

The line, from homepage.views import home, imports the home function from the views.py 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...