On 12/08/2014 12:40 PM, Craig Jones wrote:
I know that this is a common question and I have seen many, many answers
when I google about this, but I need some advice.

What I have is a field in my models called entered_by which is
ForeignKey to the User model. I would like to have this filled
automatically upon creation in the Admin panel

This is easy ... https://docs.djangoproject.com/en/1.6/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model ... but see below for a refactored way.

*and* outside of the
admin panel (regular site).  AND... I am thinking of running the site
through a load balancer so as far as I understand I believe I need a
thread safe method.

I have seen answers that use the Form, others that use Middleware, and
others that use a cache mechanism etc.  But I am having a hard time
judging which method is simple but that would work.

There are two cases: Database is updated exclusively via Django forms (or your API); and database is updated independently of your code.

In the latter case, I would give up now. In the former, write a utility method like record_user(self, request, obj, form, change) in which you try obj.entered_by = request.user followed by obj.save() and do whatever seems appropriate if there is an Exception. Also, you might want 'Anonymous' if there is no request.user.

Then in each admin class ...
    save_model = record_user # without parens

I haven't got as far as using this in the API and other Django forms but I'd be surprised if it couldn't be made to work there too.

I have no idea about thread safety but I believe the request is handled in a single thread so it should be ok.

Mike


What would you recommend I do using current technology (Django 1.6 or 1.7)?

--
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 [email protected]
<mailto:[email protected]>.
To post to this group, send email to [email protected]
<mailto:[email protected]>.
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/979d7e6f-cdff-4d02-bc65-6dbd6d4992e2%40googlegroups.com
<https://groups.google.com/d/msgid/django-users/979d7e6f-cdff-4d02-bc65-6dbd6d4992e2%40googlegroups.com?utm_medium=email&utm_source=footer>.
For more options, visit https://groups.google.com/d/optout.

--
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 [email protected].
To post to this group, send email to [email protected].
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/53E99C4D.2070907%40dewhirst.com.au.
For more options, visit https://groups.google.com/d/optout.

Reply via email to