On Tue, Oct 14, 2014 at 4:46 PM, Collin Anderson <cmawebs...@gmail.com> wrote: > Hi Ken, > > If you _really_ want it to be automatic, I think your best bet is to use a > middleware to store the user or request object in a "thread local" variable, > and then have a pre_save signal set the last_updated_by field based on that. > That method is frowned upon, but should work.
To expand on this, it is frowned on because it uses magic to achieve the desired outcome. Since it is magic, the developer stops providing anything, if the magic stops working or doesn't happen, the developer's code starts doing the wrong thing without any changes to their code. Collin suggested the usual method of providing the magic - middleware that pulls the current user in to a global variable. The model can then only be saved within the context of a request. Outside of that context, there is no middleware populating the global, so either the developer is required to do extra work outside of the context to set up the magic global so that everything works correctly, or it will fail, perhaps silently. A "better", but more involved solution would be to override save() on that model, require that an additional keyword argument "current_user" is provided. This model will now fail when you use it with code which does not supply the user, which strictly forces developers to fill in that information when using that model. Its not perfect because not everything goes through save() (although the same issue applies to using a global variable), and because you will need to customize things like ModelForms and FormSets so that they can provide the current user. Django is a web framework, you might argue that this is fine, in a web framework almost everything is in the context of a request. In very small sites this might be true, but good testing usually involves testing small blocks of code, not normally within a request context. Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users. To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CAFHbX1%2BNDumAWpswGNOk%3DA%3DT4Ymwc9Oy4FtBo-E%2B6sgKQKUY6w%40mail.gmail.com. For more options, visit https://groups.google.com/d/optout.