Resize or Modify an image before saving
Small snippet that will resize all images before they uploaded to the server.
- image
- pil
- resize
- save
- imagefield
- modified
- pre_save
- override
Small snippet that will resize all images before they uploaded to the server.
Trying to build a state-machine that stores state in the model or in settings.py rather then in the database, I wrote this small generic pre_save hook that lets me leave all the data in the Model.
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
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.
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.)
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
6 snippets posted so far.