Hi Team,
I am a rookie on Django world, and I am facing with the following problem, and after spending many hours trying to figure out a solution browsing the internet I came here to ask for helping.
Basically, I need to know how to capture the user who create a record and save it in created_by field on DB, and of course I need to do the same when any user modified a existing record and save in last_modified_by field.
I have this model named Member on models.py
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
#from django_currentuser.middleware import get_current_authenticated_user
class Member(models.Model):
firstname = models.CharField(max_length=50)
lastname = models.CharField(max_length=50)
phone = models.IntegerField(null=True)
joined_date = models.DateField(null=True)
slug = models.SlugField(default="", null=False)
created_dt = models.DateField(auto_now_add=True, null=True)
last_modified_dt = models.DateField(auto_now=True, null=True) # Automatically set on every update
#created_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='created_by')
#updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.SET_NULL, related_name='updated_by')
created_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='created_by')
updated_by = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='updated_by')
def __str__(self) -> str:
return f"{self.firstname} {self.lastname}"
def save(self, *args, **kwargs):
# Set the author to the current user before saving
if not self.pk: # Check if it's a new instance
self.created_by = kwargs.pop('User', None)
super().save(*args, **kwargs)
on admin.py I have
from django.contrib import admin
from django.forms import ModelForm
from django.http import HttpRequest
from .models import Member
# Register your models here.
#@admin.register(Member)
class MembersAdmin(admin.ModelAdmin):
list_display = ("firstname", "lastname", "joined_date")
prepopulated_fields = {"slug": ("firstname", "lastname")}
admin.site.register(Member, MembersAdmin)
I tried to use something named serializers but it did not work either.
So, when I checked the admin session on the web, I found the fields “created_by” and “last_mofidied_by” but instead of capure the logged user, and save it, the field is shown as a dropdown listing the two users I have created.
I tried different things, but I am still not able to find out how to implement that on django
If you need further information about views.py or settings.py please let me know.