Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to monkey patch django function?

Tags:

python

django

I want to customize django admin change_list_result row content, so i guess override related to change_list_result function.

And I found to konw call display_for_field via items_for_result in django.contrib.admin.templatetags.admin_list. admin_list.py

I put following code to the manage.py, but doesn't work.

from django.contrib.admin.utils import display_for_field
from warehouse.monkey_patching import _display_for_field_mod

display_for_field = _display_for_field_mod
like image 538
Peter Poon Avatar asked Dec 06 '25 19:12

Peter Poon


1 Answers

Here you override the local variable dispaly_for_field. If you want to override it, you need to set the attribute of the module:

from django.contrib.admin import utils
from warehouse.monkey_patching import _display_for_field_mod

utils.display_for_field = _display_for_field_mod

As you probably already know, you must make sure that you monkey patch the function before other modules import it, since otherwise, these will obtain a reference to the "old" function. You thus probably should import this as (one of the) first lines in your manage.py file.

like image 94
Willem Van Onsem Avatar answered Dec 08 '25 07:12

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!