0

I want to autocomplete 2 fields:

created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='created_by')
updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='updated_by')

for normal users and for django admin.

If for normal users I can use get request.user from my view(found some solutions here on the site),but this is not the case for admin/staff because I don't control the views, so I'm searching for a solution at the Model level by overwriting the save function.

Brown Bear
  • 19,655
  • 10
  • 58
  • 76
user3541631
  • 3,686
  • 8
  • 48
  • 115

3 Answers3

1

May be the solution with default user by Middleware help you.

django-populate-user-id-when-saving-a-model

Arpit Solanki
  • 9,567
  • 3
  • 41
  • 57
Brown Bear
  • 19,655
  • 10
  • 58
  • 76
  • post relevant part of the solution in the question itself. Link only answers are not acceptable – Arpit Solanki Aug 13 '17 at 14:35
  • thanks, but is a 8 year old thread so I thought there is something better for Django 1.11; using a middleware means that I push it everywhere and I don't really want that – user3541631 Aug 21 '17 at 17:30
1
from django.contrib.auth.models import User

created_by = models.ForeignKey(User, related_name='created_by')

updated_by = models.ForeignKey(User, related_name='updated_by')

Then in your view, you can do this :

form.created_by = request.user
form.updated_by = request.user

It's going to autocomplete by the current user who made the action.

May be I didn't understant your question, so may be this is what you're looking for : How to auto insert the current user when creating an object in django admin?

  • with the view I know, but in admin I don't control the view. The link helped me, I modified the answer from that post, to make a distinction between when is created and when is changed – user3541631 Aug 21 '17 at 17:33
0

is pretty simple, just add to your field: editable=False Like this:

created_by = models.ForeignKey(settings.AUTH_USER_MODEL, editable=False, related_name='created_by')
  • my need to get request.user in both normal model and admin model/form, nothing to do with "editable=False". If I don't get this info the field/foreign key will be empty/blank/null, which will give an error – user3541631 Aug 21 '17 at 17:28