简体   繁体   中英

How to save user that created and modified a record in django admin site?

I have a ReportModel in my django app with 2 field create_user (represents the user that created the report) and write_user (represents the user that last modified the report). I want to automatically save that two fields according to the user that is logged in on django admin site. How do I do that? Here is the definition of the model

class ReportModel(models.Model):


    name = models.CharField(verbose_name=_("Nombre"), max_length=50, blank=False, null=False)
    location = models.PointField(verbose_name=_("Localización"), srid=4326, blank=False, null=False)
    report_type_id = models.ForeignKey("ReportTypeModel", verbose_name=_("Tipo"),
                                                 blank=True, null=True, on_delete=models.SET_NULL,
                                                 related_name="reports")
    start_date = models.DateField(verbose_name=_("Fecha inicio"))
    end_date = models.DateField(verbose_name=_("Fecha fin"))
    create_user = models.ForeignKey(User, on_delete=models.CASCADE, 
                                   related_name='+', verbose_name=_('Creado por'), editable=False, null=True, blank=True)

    write_user = models.ForeignKey(User, on_delete=models.CASCADE, 
                                   related_name='+', verbose_name=_('Modificado por'), editable=False, null=True, blank=True)

    def __str__(self):
        return self.name

you can override the create and update methods in your serializer. In the methods before you call the super class update and create methods, you can add the fiels by your self from the request.user

something like

def create(self, validated_data):
        """
        Overriding the default create method of the Model serializer.
        :param validated_data: data containing all the details of your model
        :return: returns a successfully created record
        """
        validated_data.update({"create_user": request.user})
        # call super class create method here by passing the modified validated_data
        return student

In order to capture/record the user who performed a create/update on a model in the django admin, override the save_model method on the admin view. In the ReportModel admin view declared in admin.py file, override the save_model method as follows:


from models import ReportModel
from django.contrib import admin

@admin.register(ReportModel)
class ReportModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        if not obj.pk:
            obj.create_user = request.user #create_user should only be set once
        obj.write_user = request.user #write_user can be set at all times
        super().save_model(request, obj, form, change)


Reference: How to associate model with current user while saving

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM