I want to create a reusable function in Django

3.9k Views Asked by At

I am new to django and have been working on a project where i need to send regular mails to my clients from different modules in my django project.

I wanted to know if there is any provision in django using which i can create a reusable component which can be used globally in my project.

The purpose is to create a mail sending function using a third party api and to call it from anywhere in my application just by passing the required parameters.

2

There are 2 best solutions below

3
On

Assuming that you have a single django app in your project, you could define all your reusable methods inside a methods.py file in your app folder and then import it to use the functions.

If you have multiple apps, Then define create this methods.py in one of your app. Now lets say your project name is coolprojectname and the name of app which has methods.py is appwithmethodsscript, then you can use

from coolprojectname.appwithmethodsscript import methods

Reference

2
On

Django follows the rules of python.

As such, you can define a function anywhere, and import it wherever you want to use it.

The only condition for this to work is to have your packages following the right structure (i.e. a directory that has an __init__.py file)