Login

PreSaveMiddleware

Author:
pterk
Posted:
November 20, 2007
Language:
Python
Version:
.96
Score:
1 (after 3 ratings)

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
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from django.dispatch import dispatcher
from django.db.models import signals

PRE_SAVE_REQUEST = None

class PreSaveMiddleware(object):
    """ 
    This bit of middleware just saves the request in a global variable
    that can be used to pass the request on to any pre_save methods in
    your models
    """

    def process_request(self, request):
        global PRE_SAVE_REQUEST
        PRE_SAVE_REQUEST = request

def pre_save(**kwargs):
    instance  = kwargs['instance']
    if getattr(instance, 'pre_save', None):
        instance.pre_save(PRE_SAVE_REQUEST)

dispatcher.connect(pre_save, signal=signals.pre_save)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.