Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to monkey patch Django?

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:

  1. Where would I put the monkey patching code?

  2. When is the code run -- just once? once per Python interpreter startup? once per request?

  3. 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?

like image 380
Continuation Avatar asked Jul 16 '11 23:07

Continuation


People also ask

What is monkey patching in Django?

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.

How does a monkey patch work?

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.

What is monkey Patch_all ()?

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.


1 Answers

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
like image 113
suhailvs Avatar answered Oct 04 '22 18:10

suhailvs