Thursday, March 14, 2013

Re: Can anyone give me a suggestion or a recommendation as to how I can access the current user's username in the models.py?



On Fri, Mar 15, 2013 at 11:58 AM, Mike Dewhirst <miked@dewhirst.com.au> wrote:
On 15/03/2013 10:31am, Russell Keith-Magee wrote:


On Fri, Mar 15, 2013 at 5:24 AM, Shawn Milochik <shawn@milochik.com
<mailto:shawn@milochik.com>> wrote:

    I've repeatedly asked about this over the past couple of years and
    there seems to be no "right" answer." This, to me, is the biggest flaw
    in Django.


There's definitely a right answer.

Russell

What is the right way to design a system whereby on every save for every model the updated_by column is changed to the user.id of the logged-in user? This has to happen whether updates are done via views or the Django-Admin.

And I'm saying anonymous users can't update at all.

The brief version?

class MyModel(Model):
   ...
   def save(self, user, *args, **kwargs):
       self.updated_by = user
       return super(MyModel, self).save(*args, **kwargs)
 
From there, you just need to follow that path back to the place where the model is saved by the form. All the admin save handlers have access to the request, from which you can extract the user; form construction in the admin is also abstracted behind an interface, so you can modify the arguments passed to the form at time of construction; and forms can be modified to pass down the user data as needed to the call to save().

Now - I'm not for a second claiming that this is something that Django does well -- but it *can* be done (I know, because I've done it). 

And, more to the point, I'd look very sympathetically on any proposal or patch that made it easier to do this sort of thing -- a lot more sympathetically than I would on saying "This is hard, lets go shopping and use lots of global variables".

Yours,
Russ Magee %-)

--
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+unsubscribe@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?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate