0

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?

Mad Wombat
  • 14,490
  • 14
  • 73
  • 109
  • 2
    [this](http://stackoverflow.com/questions/6791911/execute-code-when-django-starts-once-only) might help you. – Harrison Aug 24 '16 at 14:45
  • 3
    *I am trying to hack built-in User model* <= This is where I stopped, because [you can much easier provide a custom user model](https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#specifying-a-custom-user-model). It's even documented how to change the username field. Monkey patching the model is not a good idea. – dhke Aug 24 '16 at 14:48
  • @dhke I cannot convert a multi-megabyte codebase to a custom user model. – Mad Wombat Aug 24 '16 at 14:58
  • @Harrison I will try the middleware approach – Mad Wombat Aug 24 '16 at 15:00
  • 1
    @MadWombat Not if it's referencing `contrib.auth.models.User` everywhere, yes *sigh*. – dhke Aug 24 '16 at 15:08
  • Yeah, it is using old school "user profile" approach – Mad Wombat Aug 24 '16 at 17:49

1 Answers1

1

I agree with the comments; there are prettier approaches than this.

You could add your code to the __init__.pyof your app