4

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.

Vivek Cu
  • 127
  • 1
  • 2
  • 9
  • You can define function inside any app. Also you can use it anywhere in your application – itzMEonTV Sep 21 '17 at 07:30
  • @itzMEonTV 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. Thanks – Vivek Cu Sep 21 '17 at 08:48

2 Answers2

6

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

Anuj
  • 994
  • 11
  • 21
  • Dashes (`-`) aren't allowed in module names, and module names should be lower case. – AKX Sep 21 '17 at 07:45
  • Thanks @Anuj 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. Thanks – Vivek Cu Sep 21 '17 at 08:47
  • @VivekCu If you were satisfied with the answer can you mark it as the correct answer? – Anuj Jul 20 '20 at 03:34
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)

Adelin
  • 7,809
  • 5
  • 37
  • 65
  • Thanks @Adelin 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 anyway – Vivek Cu Sep 21 '17 at 08:45
  • 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 such – Adelin Sep 21 '17 at 09:00