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?

6
  • 2
    this might help you. Commented Aug 24, 2016 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. It's even documented how to change the username field. Monkey patching the model is not a good idea. Commented Aug 24, 2016 at 14:48
  • @dhke I cannot convert a multi-megabyte codebase to a custom user model. Commented Aug 24, 2016 at 14:58
  • @Harrison I will try the middleware approach Commented Aug 24, 2016 at 15:00
  • 1
    @MadWombat Not if it's referencing contrib.auth.models.User everywhere, yes sigh. Commented Aug 24, 2016 at 15:08

1 Answer 1

1

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

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

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

1 Comment

Models are not loaded by the time __init__.py is parsed

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.