Login

Tag "signals"

Snippet List

Add custom fields to the built-in Group model

Add fields and extend Django's built-in `Group` model using a `OneToOneField` (i.e. a profile model). In this example, we add a `UUIDField`. Whenever a new group is created, we automatically (via signals) create a corresponding `Role` record referencing the newly created group. Whenever a Group is deleted, the corresponding Role is deleted as well.

  • model
  • group
  • uuid
  • signals
Read More

Pre-delete signal function for deleting files a model

This snippit is meant to be used with the pre_delete signal to delete any files associated with a model instance before the instance is deleted. It will search the model instance for fields that are subclasses of FieldFile, and then delete the corresponding files. As such, it will work with any model field that is a subclass of FileField.

  • remove
  • delete
  • signals
  • file
Read More

Binding signals to abstract models

Intro ----- I found a question on SO for which Justin Lilly's answer was correct but not as thorough as I'd like, so I ended up working on a simple snippet that shows how to bind signals at runtime, which is nifty when you want to bind signals to an abstract class. Bonus: simple cache invalidation! Question -------- [How do I use Django signals with an abstract model?](http://stackoverflow.com/questions/2692551/how-do-i-use-django-signals-with-an-abstract-model) I have an abstract model that keeps an on-disk cache. When I delete the model, I need it to delete the cache. I want this to happen for every derived model as well. If I connect the signal specifying the abstract model, this does not propagate to the derived models: pre_delete.connect(clear_cache, sender=MyAbstractModel, weak=False) If I try to connect the signal in an init, where I can get the derived class name, it works, but I'm afraid it will attempt to clear the cache as many times as I've initialized a derived model, not just once. Where should I connect the signal? Answer ------ I've created a custom manager that binds a post_save signal to every child of a class, be it abstract or not. This is a one-off, poorly tested code, so beware! It works so far, though. In this example, we allow an abstract model to define CachedModelManager as a manager, which then extends basic caching functionality to the model and its children. It allows you to define a list of volatile keys that should be deleted upon every save (hence the post_save signal) and adds a couple of helper functions to generate cache keys, as well as retrieving, setting and deleting keys. This of course assumes you have a cache backend setup and working properly.

  • managers
  • models
  • cache
  • model
  • manager
  • signals
  • abstract
  • signal
  • contribute_to_class
Read More

User Profile minimal code

Usually I start an authentication app with this model. Don't forget to set it up in the settings file AUTH_PROFILE_MODULE = 'authentication.UserProfile'

  • user
  • profile
  • signals
  • get_profile
Read More

Run model validation before saving a model instance

How to validate your model at save using the pre_save signal. from http://groups.google.com/group/django-developers/browse_thread/thread/eb2f760e4c8d7911/482d8fd36fba4596?hl=en&lnk=gst&q=problem+with+Model.objects.create#482d8fd36fba4596

  • save
  • clean
  • pre_save
  • signals
  • validate
  • full-clean
  • full_clean
Read More

immitating 'real' post_syncdb signal

I did not like the idea of having to load fixtures by creating a huge initial_data.json file. I also did not want to store my initial data in a bunch of <modelname>.sql files. Django has post_syncdb signal which fires when model(s) for an application are installed, but I needed something that would run only *once* at the end of syncdb command, at least after all of the models are installed, and here's what I've come up with. The code basically checks if the current callback is for the last app in your INSTALLED_APPS, and if so, executes some fixture loading code.

  • signals
  • post_syncdb
Read More

Signal to notify new saved comments

Signal to notify new saved comments. **Example:** from django.contrib.comment import models, signals signals.comment_was_posted.connect(new_comment_notifier, sender=models.Comment)

  • django
  • python
  • comments
  • signals
Read More

Execute a signal once

Decorates signals for executing only one time Exemple usage : from django.core.mail import EmailMultiAlternatives from django.template.loader import render_to_string from django.contrib.auth.models import User @one def user_welcome(sender, instance, created, **kwargs): # Send a welcome email if created == True and isinstance(instance, User): instance.message_set.create(message=_(u"Ho, Welcome %s!" % instance)) subject, from_email, to = 'Welcome !', '[email protected]', instance.email text_content = render_to_string('mail/welcome.html', { 'user': instance }) msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.send()

  • decorator
  • signals
  • once
Read More

CustomImageField for Django 1.0 alpha

The venerable CustomImageField, invented by [Scott Barnham](http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/) and rejiggered for newforms-admin by [jamstooks](http://pandemoniumillusion.wordpress.com/2008/08/06/django-imagefield-and-filefield-dynamic-upload-path-in-newforms-admin/#comments). This here is a stab at a [post-Signals-refactor](http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges#Signalrefactoring) version. Seems to do 'er. Note: This should be pointless once [fs-refactor](http://code.djangoproject.com/ticket/5361) lands.

  • models
  • fields
  • imagefield
  • newforms-admin
  • signals
Read More

Alter Column Lengths of Contrib Apps

If you want to modify the length of a column of a contrib application, you can either modify django (cumbersome) or you can run a post_syncdb signal hook. Related: [Ticket 4748](http://code.djangoproject.com/ticket/4748)

  • signals
Read More

PreSaveMiddleware

With this middleware in place (add it to the MIDDLEWARE_CLASSES in your settings) you can pass a request to the model via a pre_save method on the model. I'm not sure if it is an improvement over the [threadlocals method] (http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser) but it may be an alternative that can be improved upon? class MyModel(models.Model): name = models.CharField(max_length=50) created = models.DateTimeField() created_by = models.ForeignKey(User, null=True, blank=True) def pre_save(self, request): if not self.id: self.created_by = request.user

  • middleware
  • pre_save
  • signals
Read More

14 snippets posted so far.