[Django]-How to monkey patch Django?

9👍

You could put it anywhere, but it’s common to see this kind of stuff linked in the settings file (or even the urlconf). Anywhere you could put a signal might also be appropriate. This code should really be slightly more intelligent – often files get imported more than once and there’s not a lot you can do about it, so you can run into problems if you try to run code like this multiple times.

The code needs to be executed at least once for each python process.

Yes you would need to change the DB by hand. Syncdb probably wouldn’t catch the change (I haven’t looked closely at the code), but there might be some places you could put the code that would work.

You seem to already know that this is a terrible, horrible thing to do and should never be done for real code, so I won’t belabor that point. Doing this kind of thing is a fantastic way to generate really difficult to find bugs in your code, in addition to code that may not work in future versions of Django.

Also, it won’t work well with South, which you should be using.

20👍

put the file monkey_patching.py in any of your apps and import it in app’s __init__.py file. ie:

app/monkey_patching.py

#app/monkey_patching.py
from django.contrib.auth.models import User

User.add_to_class('openid', models.CharField(max_length=250,blank=True))

def get_user_name(self):
    if self.first_name or self.last_name:
        return self.first_name + " " + self.last_name
    return self.username

User.add_to_class("get_user_name",get_user_name)

app/__init__.py

#app/__init__.py
import monkey_patching

2👍

Using both @suhailvs and @Paul McMillan’s suggestions I added a patch.py file to the root of my app, and inside the app’s apps.py called my patched in the ready signal:

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    name = "MyApp"

    def ready(self):
        """
        Called when the app is ready.
        """
        from .patch import patch_func

        patch_func()

The AppRegistryNotReady: Apps aren't loaded yet. happens because of the import, not the function call, so it must be inside the function.

👤felipe

Leave a comment