Monkey-patch your apps in a simple and elegant manner — Django

Keep your patches locally and toggle them with ease

When we are testing one of our applications’ flows which consists of multiple steps that include filling forms (e.g., customer registers, fills product details and an administrator verifies the information in a classified ads platform) it can be quite repetitive to input every single field everytime.

One way to help with this is to fill the dictionary of the view’s get_initial method which will make your form already load with the needed data:

This works but is not recommended since you are mixing actual code and logic with temporary stuff that can confuse you and even be problematic to others if added to your repository by mistake.

When you remember that you commited your help code

We can improve on this by using a technique called monkey-patching. After making the adjustments, we have an isolated code block that can easily be removed or changed without interfering with the actual logic:

But having this in the views.py file is still a problem because it’s in a place shared by all of your team and you have to keep track of removing it everytime you commit the code.


The ideal solution would be to completely remove references in files that are actively changed by your team and make it easier for you to use, change or disable these patches.

We can achieve this by moving the monkey-patch block to your local settings file (if you are not familiar, here’s a reference on this configuration) but then, due to how Django load your project’s files, it is necessary to wrap your code in a function and call it in your project’sAppConfig:

And with that, whenever your view is loaded, your form will be filled and you don’t need to worry about it interfering with your VCS anymore (since your local configuration file should be already ignored).

But please be a good developer and test (and even unit-test!) your code thoroughly with your monkey-patches disabled and with different inputs so you won’t end up with unexpected problems in production when people start using your website for real.


We can even improve and add a simple structure to enable and disable the monkey-patching so it’s even easier to use them:

So instead of erasing or commenting your blocks, just use the flags to turn them on or off as needed and reload your server to see the changes.


All the source code shown and explained here (mixins, functions, examples, samples, etc.) is available in the GitHub repository below along with other helpful projects I’ve developed and wrote about. Feel free to check it out, use them in your own work and help me improve them with your feedback.

🍋 🍋 🍋