I came upon this post on monkey patching Django:
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)
I understand that this isn't ideal and it's better to add fields and functions to User
through a separate model Profile
.
With that said, I just want to understand how this would work:
Where would I put the monkey patching code?
When is the code run -- just once? once per Python interpreter startup? once per request?
Presumably I'd still need to change the DB schema. So if I dropped the table User
and ran ./manage.py syncdb
, would syncdb
"know" that a new field has been added to User
? If not how do I change the schema?
Monkey patching refers to the dynamic (run-time) modification of a class or module. It is an advanced topic in Python and to understand it one must have clarity about functions and how functions are treated in Python.
A monkey patch is a way to change, extend, or modify a library, plugin, or supporting system software locally. This means applying a monkey patch to a 3rd party library will not change the library itself but only the local copy of the library you have on your machine.
According to Wikipedia: In Python, the term monkey patch only refers to dynamic modifications of a class or module at runtime, motivated by the intent to patch existing third-party code as a workaround to a bug or feature which does not act as you desire.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With