pythondjangodjango-admindjango-authentication

Save the current user when saving a model in Django admin backend


I'd like to store the user that saved a model for the first time in one of the fields of that model. This is what I have.

models.py:

from django.conf import settings
class Project(models.Model):
[...]
    added_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.PROTECT)

    def save_model(self, request, obj, form, change):
        if not obj.pk:
            obj.added_by = request.user
        super().save_model(request, obj, form, change)

settings.py:

AUTH_USER_MODEL = 'auth.User'

The request.user appears to be always empty (I'm logged in as root to the /admin). What am I missing?


Solution

  • This does not belong in the model, but in the ModelAdmin:

    from django.contrib import admin
    
    
    @admin.register(ModelAdmin)
    class ProjectAdmin(admin.ModelAdmin):
        # …
    
        def save_model(self, request, obj, form, change):
            if obj._state.adding:
                obj.added_by = request.user
            return super().save_model(request, obj, form, change)