Django: Where to put helper functions?

PythonDjango

Python Problem Overview


I have a couple of functions that I wrote that I need to use in my django app. Where would I put the file with them and how would I make them callable within my views?

Python Solutions


Solution 1 - Python

I usually put such app specific helper function in file utils.py and use someting like this

from myapp.utils import my_cool_func

def view_coolness(request):
    data = my_cool_func(request)
    return render_to_response("xxx.html")

but it depends what you helper does, may be they modify request , the could be part of middleware, so you need to tell what exactly those helper functions do

Solution 2 - Python

create a reusable app that include your generic functions so you can share between projects.

use for example a git repo to store this app and manage deployments and evolution (submodule)

use a public git repo so you can share with the community :)

Solution 3 - Python

If they are related to a specific app, I usually just put them in the related app folder and name the file, 'functions.py'.

If they're not specific to an app, I make a commons app for components (tests, models, functions, etc) that are shared across apps.

Solution 4 - Python

I am using new python file service.py in app folder. The file contains mostly helper queries for specific app. Also I used to create a folder inside Django application that contains global helper functions and constants.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionThe.Anti.9View Question on Stackoverflow
Solution 1 - PythonAnurag UniyalView Answer on Stackoverflow
Solution 2 - PythonjujuleView Answer on Stackoverflow
Solution 3 - PythonmonkutView Answer on Stackoverflow
Solution 4 - PythonTomas TomecekView Answer on Stackoverflow