0

I have a simple signal in my project, that checks which fields have been updated in the form. I also need to check the user who changed data in those fields.

Request.user doesn't seem to work here.

@receiver(sender=BackOperator, signal=pre_save)
def change_log(**kwargs):
    instance = kwargs['instance']
    try:
        original_object = BackOperator.objects.using('operator').get(pk=instance.pk)
    except:
        return
    if original_object:
        field_names = [field.name for field in original_object._meta.fields]

        for field in field_names:
            try:
                ori_field = getattr(original_object, field)
                new_field = getattr(instance, field)
                message = (field + ": " + str(ori_field) + " changed to: " + str(new_field))
                if ori_field != new_field:
                    BackNote.objects.using('operator').\
                        create(operator=instance.pk, note=message)
            except:
                return

I'd like to add a user's username as a string to message, that is saved in the BackNote table.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
ZmuA
  • 151
  • 1
  • 13

1 Answers1

0

Do you have several options:

  1. Include a FK to User on BackOperator. Ex: LastAccessByUser=models.ForeignKey(User ... Fill LastAccessByUser on your views.

  2. Use a package like django-currentuser to access current user.

For me, the first solution is cleaner than second one, that looks like an anti pattern.

dani herrera
  • 48,760
  • 8
  • 117
  • 177