Monday, October 20, 2014

Re: How to "automatically " populate "last_updated_by" DB columns with the current user's id

Hi Ken,

On 10/18/2014 12:55 PM, Ken Winter wrote:
> OK, I've written and unit-tested the database components - see
> https://drive.google.com/file/d/0B-thboqjuKZTSjRHTXhqMlo3RlU/view?usp=sharing.
> Now I could use a little advice on the Django part.
>
> I believe that all that is needed is to have the app call the DB
> function set_session_user() while logging in the user, passing it the
> user id. I guess my questions are:
>
> 1. Where to put this call? - i.e. in what Django module and function?

I would not edit any module or function in Django. Editing Django
directly is just asking for trouble when you want to upgrade Django in
the future.

Fortunately, as in many cases, Django provides the extension hooks
necessary to do what you want without editing any Django code. There are
two techniques that come to mind:

1) You can write your own login view to replace (or wrap)
`django.contrib.auth.views.login`, which does the necessary database query.

2) You could write your own authentication backend (see
https://docs.djangoproject.com/en/1.7/topics/auth/customizing/),
probably just subclassing the default ModelBackend and adding your
database query in an overridden `authenticate()` method after
`ModelBackend.authenticate()` successfully authenticates the user.

Option 1 is simpler if your app has a typical login flow that always
goes through a single login view. Option 2 is lower-level and perhaps
more comprehensive if your app has multiple login flows/views.

> 2. How to make the call? - Is it just executing a SQL statement like
> "SELECT set_session_user(<userid>)", or is there a better way?

I'm not sure what a "better way" would be; Django does not provide any
built-in API to call arbitrary database stored procedures, so you will
have to do this using raw SQL with `cursor.execute()`.

Carl

--
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.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/544550E7.7070408%40oddbird.net.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment