Search code examples
pythondjangodjango-modelsdjango-viewsdjango-request

Django request.user is model, for admin and normal user


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.


Solution

  • 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?