0

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.

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This is a better approach that the one I've suggested if you don't have any models that you want to extend in it. If you do, do create a template app and use class hierarchy
That's a start, but then one model in one app will be calling "post_save.connect(update_groups)" and it will be kind of arbitrary which app does that. I was hoping there was a concept of a site-wide models.py or some other module that gets imported early.
@Greg, I think that custom modules are best way to share a code in this case. As for the signals, you need to specify the sender, ofcourse, then django will know which model has sent it.
That <would work> but the code isn't specific to any one app, so why should any one app import helper and call the signal? It seems like there should be a way to preload site-wide stuff.
2

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

2 Comments

This is an interesting info. Can you provide a link on creating template apps?
that's more software design knowledge than django itself, still, refer to the following: docs.djangoproject.com/en/dev/topics/db/models/… ||| docs.python.org/tutorial/classes.html#inheritance ||| diveintopython.org/object_oriented_framework/… || Good luck
1

__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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.