Skip to main content

Monkey Patching Django Model Class

Django is shipped with some useful application, also there are lots of third party re-usable application written for Django. Sometime you need to modify or customize these applications(Models of application) to meet your software requirements. One of the usual solution is adding a Model class to have a one-to-one relationship with the third party Models. This solution has some disadvantages such as having more tables and classes which can highly adversely affect database performance, scalability and add more complexity to the software development. 
I think of another solution to this problem. I used Django South along with monkey patching of third party Model classes. I added a field to Django user class. Here is a walk through over this approach.

1. Add an application:
python manage.py startapplication userpatch

2. Add the following  code to add the new field to the user class

from django.db import models
from django.contrib.auth.models import User

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

3. Add this field to User admin interface: (This can be done in either admin.py or models.py)

from django.contrib.auth.admin import UserAdmin
UserAdmin.list_display += ('open_id',)
UserAdmin.fieldsets[0][1]['fields'] += ('open_id',)

4. add the application to INSTALLED_APP in project settings file. 

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    # Uncomment the next line to enable the admin:
    'django.contrib.admin',
    'south',
    'userpatch',
    # Uncomment the next line to enable admin documentation:
    # 'django.contrib.admindocs',



5. By default South stores the migration files inside the app folder. Since we might have different app using  the same Django installation we want to save these files in different location. As of South 0.7 you can define location where South access the migration files. Add the following dictionary to the project settings file change the default migration directory.

SOUTH_MIGRATION_MODULES = {
    'auth': 'userpatch.migrations',
}

6. Run the schemamigration and migrate for this application.
python manage.py schemamigration userpatch --auto
python manage.py migrate userpatch

NOTE: I assumed that you have already added the application to South.



Comments

  1. This is a very useful article that explains how monkey patching can be used to extend and customize Django model classes without modifying the original source code. The walkthrough demonstrates practical techniques for adding fields dynamically, integrating them with the admin interface, and managing database migrations efficiently. Such approaches provide developers with flexible ways to adapt third-party applications while maintaining clean and reusable code structures.

    ReplyDelete
  2. Django's extensibility and Python's dynamic features make it easier to build scalable web applications and customize frameworks according to project requirements. The concepts discussed in this article are highly relevant for students and developers working on Python Projects For Final Year, where web development, framework customization, and database integration are important areas of application development.

    ReplyDelete
  3. Understanding advanced Python programming concepts such as monkey patching, object-oriented design, and framework internals can significantly improve software development skills and application architecture. Learning these concepts through structured programs such as Python Training Courses helps students gain practical experience in building robust and maintainable Python-based applications.

    ReplyDelete

Post a Comment

Popular posts from this blog

Installing Django on IIS 7 Using PyISAPIe

PyISAPIe is an ISAPI extension which can be downlod from here . Download the latest extension according to installed python version. Just make sure that ISAPI and ISAPI filters has been installed on IIS (During IIS installation these two component should have checked). Copy PyISAPIe.dll file and Http folder into your Django website project.Example: Suppose your website folder path is: "C:\Python25\Lib\site-packages\MySite" "C:\Python25\Lib\site-packages\MySite\PyISAPIe.dll" and "C:\Python25\Lib\site-packages\MySite\Http" will be the result. Copy and replace the isap.py from "PyISAPIe\Examples\Django" folder to "C:\Python25\Lib\site-packages\MySite\Http" IIS need to have access to your project folder and also django folder. so you need to give access "Network Service" to these folder. Right click on site folder "C:\Python25\Lib\site-packages\MySite"  click on properties. On properties window choose the sec...

Installing MS SQL Server driver on Ubuntu Linux

Although making a connection to SQL Server can be done using unixODBC and FreeTDS, it does not work with some collations on SQL Server 2008. Recently, Microsoft released an ODBC driver for Linux that works on 64-bit systems only. Installing the driver is tricky. I begin by installing the build-essential, which is required for compiling from source. Checkinstall can be installed if you want to add the following application to the package manager. $ sudo apt-get install build-essential  Download unixODBC-2.3.0  and Microsoft ODBC dirver  and extract. $ sudo wget ftp://ftp.unixodbc.org/pub/unixODBC/unixODBC-2.3.0.tar.gz $ tar xvf unixODBC-2.3.0.tar.gz $ wget http://download.microsoft.com/download/6/A/B/6AB27E13-46AE-4CE9-AFFD-406367CADC1D/Linux6/sqlncli-11.0.1790.0.tar.gz $ tar xvf sqlncli-11.0.1790.0.tar.gz  Install the unixodbc using the following commands: $ ./configure --disable-gui --disable-drivers --enable-iconv --with-iconv-char-enc=UTF8 --with-ico...

Installing pyodbc on ubuntu

Installing pyodbc is straight forward but if  getting     "error: command 'gcc' failed with exit status 1"  when installing pyodbc, make sure you have installed  requirements  as below. sudo apt-get install unixODBC-dev g++ pip install pyodbc