Reputation: 15105
I need to run some code every time my application starts. I need to be able to manipulate models, just like I would in actual view code. Specifically, I am trying to hack built-in User model to support longer usernames, so my code is like this
def username_length_hack(sender, *args, **kwargs): model = sender._meta.model model._meta.get_field("username").max_length = 254
But I cannot seem to find the right place to do it. I tried adding a class_prepared signal handler in either models.py or app.py of the app that uses User model (expecting that User will by loaded by the time this apps models are loaded). The post_migrate and pre_migrate only run on migrate command. Adding code into settings.py seems weird and besides nothing is loaded at that point anyway. So far, the only thing that worked was connecting it to a pre_init signal and having it run every time a User instance is spawned. But that seems like a resource drain. I am using Django 1.8. How can I run this on every app load?
Upvotes: 0
Views: 280
Reputation: 783
I agree with the comments; there are prettier approaches than this.
You could add your code to the __init__.py
of your app
Upvotes: 1