I want to create a reusable function in Django
Asked Answered
H

2

5

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.

Harvard answered 21/9, 2017 at 7:27 Comment(2)
You can define function inside any app. Also you can use it anywhere in your applicationGravedigger
@Gravedigger yes i do know of that option existing in Django. I just needed to know if i can create a separate file/function which is not related to any modules but only to that purpose for which it is being used. ThanksHarvard
G
7

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

Gynaeco answered 21/9, 2017 at 7:31 Comment(3)
Dashes (-) aren't allowed in module names, and module names should be lower case.Gillespie
Thanks @Gynaeco Even i had the same thing in mind. But as some frameworks allow the option to create a common plugin like class to be called from any where i thought django also might have one. ThanksHarvard
@VivekCu If you were satisfied with the answer can you mark it as the correct answer?Gynaeco
D
4

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)

Debussy answered 21/9, 2017 at 7:34 Comment(2)
Thanks @Debussy Even i was thinking of the same process. As I didn't want the mail send (a common function) to reside in a module not related to it, i asked that question. Thanks anywayHarvard
Probably you'd be better of adding that function to the 'UserManager'. Also, don't forget that if this answers your question, it should be flagged as suchDebussy

© 2022 - 2024 — McMap. All rights reserved.