Login

Tag "pre_save"

Snippet List

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

"Autoconnect" model decorator, easy pre_save and post_save signal connection

This method allows you to define pre_save and post_save signal connections for your decorators in a little more clean way. Instead of calling `pre_save.connect(some_func, sender=MyModel)`, or perhaps `pre_save.connect(MyModel.some_static_func, sender=MyModel)`, you can simply define the pre_save method right on your model. The @autoconnect decorator will look for pre_save and post_save methods, and will convert them to static methods, with "self" being the instance of the model.

  • pre_save
  • post_save
  • signal-connect
Read More

SelfForeignKey to prevent hierarchical loops

When you have a model containing a field that is a foreign key back to the same model, you could find yourself with a hierarchy with an infinite loop: #Data modelling Back to the Future > grandfather > father > son > father > ... Using this field instead of the standard ForeignKey will ensure that no model instance is saved that has itself as an ancestor, breaking the relationship if it does. (Enhancements: I am sure one would want to better enhance this with appropriate error handling instead of silently disconnecting the relationship. And the relevant forms ought not show ancestors in the field's widget to reduce the chances of this happening in the first place.)

  • pre_save
  • recursion
  • loop
  • foreign
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

6 snippets posted so far.