Where should utility functions live in Django?

Viewed 32596

Where should utility functions live in Django? Functions like custom encrypting/decrypting a number, sending tweets, sending email, verifying object ownership, custom input validation, etc. Repetitive and custom stuff that I use in a number of places in my app. I'm definitely breaking DRY right now.

I saw some demos where functions were defined in models.py, although that didn't seem conceptually right to me. Should they go in a "utilities" app that gets imported into my project? If so, where do they go in the utilities app? The models.py file there?

Thanks for helping this n00b out.

UPDATE: Let me be even more specific. Say I need a function "light_encrypt(number)" which takes the param "number", multiplies it by 7, adds 10 and returns the result, and another function "light_decrypt(encr_number) which takes the param "encr_number", subtracts 10, divides by 7 and returns the results. Where in my Django tree would I put this? This is not middleware, right? As Felix suggests, do I create a python package and import it into the view where I need these functions?

4 Answers

It depends whether the functions are project or app specific.

The other answers are already addressing where to place it for project specific functions. More precisely, in a folder called common in the root of the project.

If we are talking about app specific, then I'd simply place it inside of the app in a file named utils.py, like

myproject/         (Django project) 
  common/  
    util/
      __init.py__    (project app specific functions)  
  myapp/
    migrations/    (myapp migrations)
    utils.py            (myapp specific functions)
    views.py
    admin.py
    forms.py
    models.py
    test.py
Related