views:

101

answers:

2

I'm trying to override the default User model in Django to add some logic into the save() method. I'm having a hard time trying to figure out out to go about this.

I'm using Django 1.1 if that helps.

I used post_save since i need to add the user into ldap.. I just added this into a models.py

from django.db import models
from django.contrib.auth.models import User
from django.db.models import signals
from django.dispatch import dispatcher


def user_post_save(sender, instance, **kwargs):
    print "got here"

models.signals.post_save.connect(user_post_save, sender=User)
+1  A: 

Don't. Instead catch the pre_save signal.

Ignacio Vazquez-Abrams
How? What would he do in the `pre_save` signal? Can you give an example of how to do it?
Dominic Rodger
@Dominic: The signal handler is passed the model before it's put into the database. You just manipulate it the way you normally would.
Ignacio Vazquez-Abrams
@dominic.. i updated my post with a example solution based on post_save signal
Mike
A: 

You'd better use a Proxy model, so to use the same table but overriding behavior.

This is the standard way to extend Django's own models, because they cannot be made abstract.

So declare your model as:

from django.contrib.auth.models import User

class CustomUser(User):
    class Meta:
        proxy = True

    def save(self, *args, **kwargs):
        # do anything you need before saving
        super(CustomUser, self).save(*args, **kwargs)
        # do anything you need after saving

and you are done.

saverio