6

I am using mongoengine and would like to run connect() after settings (not inside them as suggested in its docs). This is actually more like a general question how to run code right after all settings are loaded.

Update: I need a solution for management commands as well. Common approach is adding a middleware with exception MiddlewareNotUsed or adding code to root urls.py, but both don't work for commands.

Andrei
  • 10,918
  • 12
  • 76
  • 110
  • 3
    Does this help? http://stackoverflow.com/questions/2781383/where-to-put-django-startup-code – ustun Feb 13 '12 at 11:42
  • @ustun, if you could make your comment as an answer, I will accept it. – Andrei Feb 13 '12 at 11:50
  • 1
    Take a look at the following question, it should help: http://stackoverflow.com/questions/2781383/where-to-put-django-startup-code – ustun Feb 13 '12 at 11:50
  • 2
    I just did, but it automatically converted the answer to a comment, with the following message: "Trivial answer converted to comment" :) – ustun Feb 13 '12 at 11:52
  • Hm, it is a nice solution, but I still have the issue for management commands. I would be nice to have something more universal. – Andrei Feb 13 '12 at 12:15
  • 1
    @ustun: That's because posting a link to another SO question is not an answer in and of itself. If the question can be answered that easily, then it's most likely a dupe and should be closed. (in this case, the OP is technically wanting something additional that the other question doesn't cover, which is the only reason I haven't voted to close it.) – Chris Pratt Feb 13 '12 at 16:05
  • 1
    Note that http://stackoverflow.com/questions/6791911/execute-code-when-django-starts-once-only says the opposite of the answer linked by ustun: do not use a weird middleware but put it in the urls.py :-) – Reinout van Rees Mar 21 '12 at 23:26

1 Answers1

6

The normal place for startup-like code is in a urls.py (when you need the settings to be already loaded). Django doesn't have a good spot yet for this.

(There is an "app refactor" branch that a gsoc student worked on in 2011, but it didn't get merged into core django yet. This "app refactor" includes a solution to your very problem, but that doesn't help you...)

You mention that a management command also needs it. Is that your own management command? Nothing stops you from importing the urls.py there, is it?

This is sadly one of the few Django weak points. Luckily there aren't that many :-)

Reinout van Rees
  • 13,486
  • 2
  • 36
  • 68