Nanda
Nanda

Reputation: 21

Can I get the name of the admin who updated the record in django?

I am new to Django and I am trying to make an application and I am stuck with this.

I would like to get the name of the admin who updated the record and add save it. Is that possible?

Upvotes: 1

Views: 53

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476659

You can make an field that is a ForeignKey [Django-doc] that refers to the user model, you can limit the options to users with is_staff=True. For example:

from django.conf import settings

class MyModel(models.Model):
    # …
    editor = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        editable=False,
        limit_choices_to={'is_staff': True}
    )

In a CreateView or UpdateView, you can then alter the field to the logged in user. For example for a CreateView:

from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic.edit import CreateView

class MyModelCreateView(UserPassesTestMixin, LoginRequiredMixin, CreateView):

    # …
    
    def test_func(self):
        return self.request.user.is_staff  # only staff can access the view

    def form_valid(self, form):
        form.instance.editor = request.user
        return super().form_valid(form)

In a ModelAdmin for the MyModel, you can also attach the logged in user:

from django.contrib import admin

class MyModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.editor = request.user
        return super().save_model(request, obj, form, change)

Upvotes: 1

Related Questions