tags:

views:

108

answers:

3

I need a place to run an initialization code that is application specific (like connecting to signals). When I put the code to __init__.py module of an application I've ended up with a circular import of the models.

Is there a way to fire a function when the framework is setup and before any request is executed?

I use quite old version of django 96.6, but I'm also interested in the solutions for the current version.

Regarding the duplication of other questions: Here is how the question differ from the duplicates suggested by S.Lott in comments:

Comments to current solutions: I can't use urls as most of my apps don't have any urls exposed. They just listen to signals and store additional information in the database.

+3  A: 

Signals, specifically, are recommended to be put in the models.py of your app.

Try models.py or urls.py and let us know if you have any luck.

Ben Edwards
I can't put it in to the models as I need the function in its own module and I need to use my models in that module.
Piotr Czapla
Your signals function definition can be in a seperate file (I use signals.py -- creative, I know) but then in my models.py I add at the bottom something like post_save.connect(profile_updater, sender=MyProfile) of course with the proper imports.
ashchristopher
@ashchristopher but if your signals.py use models you end up with circular references. I don't want to import models in very signal handler.
Piotr Czapla
Ah - I understand. I dealt with this by including the import within the signal function definition.
ashchristopher
A: 

The best place for stuff like this... anywhere, just import it in your urls.py file (for obvious reasons urls are loading before any requests).

Alex Gaynor
I've hoped for anything more explicit :(
Piotr Czapla
Few of my apps don't have urls at all. (They just listen to signals and store additional information in the database)
Piotr Czapla
+1  A: 

If you don't provide urls, then you really need to put it in models.py, that's just the way it is.

Now, on to your problems: You want to define it in its own module, great, do that. To avoid a circular import, use django.db.models.get_model to return the model dynamically for you. You can provide an initialisation function for your signals module to import the relevant model and connect the relevant signals. This function would then be called at the end of models.py, being run only ever once and after your model is initialised.

There's still a chance that this wont work (if the models aren't yet ready when you set it up), but give it a try and let us know.

Will Hardy