Greg
Greg

Reputation: 47124

Django - non app specific models.py?

I have multiple Django apps, and I have some code in one of my models.py that really applies to all of the apps. Is there a way to move it somewhere generic, outside of a specific app folder?

Examples of non app specific code I have:

def update_groups(sender, user=None, ldap_user=None, **kwargs):
    ...

django_auth_ldap.backend.populate_user.connect(update_groups) 

A function to correctly identify users, and connect to the correct signal.

I also have a model proxy of django.contrib.admin.models.LogEntry and a modelAdmin of that model proxy so users in the admin site can view the change history. But these really don't belong in any one app's models.py.

Upvotes: 0

Views: 681

Answers (3)

Greg
Greg

Reputation: 47124

__init__.py in my project's directory seems to be a good place to put this stuff. It gets run right away when the server starts so it's available to everything else. It seems to work fine so far.

Upvotes: 1

tiagoboldt
tiagoboldt

Reputation: 2426

You could create a template app that could be used or extended (class hierarchy) by all your other apps that could use that code.

Upvotes: 2

Silver Light
Silver Light

Reputation: 45922

Well, just create a python module somewhere in your project and then refference it in your models. To do this, you need a directory with __init__.py file:

helpers/
   __init__.py 
   functions.py

Put your code into the functions.py and in any other place you will be able to:

from helpers.functions import update_groups
post_save.connect(update_groups)

Name of the module is up to you, ofcourse.

Upvotes: 2

Related Questions