Created
January 28, 2010 05:09
-
-
Save johnboxall/288452 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db import models | |
from django.db.models.signals import post_save | |
from django.dispatch import Signal | |
# TODO: Better call for storing the val. | |
# TODO: Could you use a function to store the old state? | |
# TODO: Does this even really belong in the app? Noooo... | |
# Should be some way to spec. which model is the Thread/Post. | |
# TODO: This use a better name. | |
# > DirtyFieldMixin? | |
# > ChangedFieldMixin? | |
# > UpdateFieldMixin | |
class SignalFieldMixin(object): | |
""" | |
If the model instance contains this field is while this field is dirty, | |
fires a signal providing the state of the model when it was first made. | |
""" | |
def value_from_object(self, obj): | |
if not hasattr(obj, "_state"): | |
obj._state = {} | |
obj._state[self.name] = obj.__dict__.get(self.name) | |
return super(SignalFieldMixin, self).value_from_object(obj) | |
def contribute_to_class(self, cls, name): | |
super(SignalFieldMixin, self).contribute_to_class(cls, name) | |
post_save.connect(self.updated, sender=cls) | |
def updated(self, instance, force=False, *args, **kwargs): | |
if hasattr(instance, "_state"): | |
fields_updated.send(sender=instance, state=instance._state) | |
# Prevent multiple signals, reset state. | |
del instance._state | |
class SignalSlugField(SignalFieldMixin, models.SlugField): | |
pass | |
fields_updated = Signal(providing_args=["state"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment