How to To automatically save the admin user by default who updates a record in Django
To automatically save the ID of the admin user who updates a record in Django, you can override the save_model
method of the admin class. Here's an example:
-
Open the file containing the admin class for your model, typically
admin.py
in your app directory. -
Import the necessary modules:
from django.contrib import admin
from .models import YourModel
- Create a new class that inherits from the default model admin:
class YourModelAdmin(admin.ModelAdmin)
: pass
- Override the
save_model
method of the model admin class:
class YourModelAdmin(admin.ModelAdmin):
def save_model(self, request, obj, form, change):
if not obj.id:
# New object is being created, set the admin user ID as the
default value
obj.admin_user = request.user
else:
# Existing object is being updated, retain the existing admin user ID
obj.admin_user_id = obj.admin_user_id
obj.save()
In the above code, admin_user
is the field in your model where you want to store the admin user ID. Adjust the field name accordingly.
- Register the model with the modified admin class in the
admin.py
file:
admin.site.register(YourModel, YourModelAdmin)
That's it! Now, whenever an admin user creates a new record, the admin_user
field will be automatically set to the ID of the admin user. When updating an existing record, the admin_user
field will retain its existing value.
Make sure to restart your Django development server for the changes to take effect