0

How can you get the user who is saving record in django signals? I am using signals to fill in data when a user marks completed = True via a form. I was hoping something like instance.User or instance.CustomUser.username would work, but it just throws errors that these don't exist in Maintenance model.

models.py

from django.db import models
from accounts.models import CustomUser
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.conf import settings
from django.db.models.signals import post_save
from django.utils.timezone import utc
import datetime
from django.utils import timezone



class Maintenance(models.Model):
    device = models.ForeignKey(get_user_model(),on_delete=models.CASCADE,)
    customerTag = models.CharField(max_length=50,)
    maintenanceItem = models.CharField(max_length=35,blank=True,)
    maintenanceDescrip = models.TextField(max_length=300,blank=True,)
    maintenanceNotes = models.TextField(max_length=300,blank=True,)
    dateCreated = models.DateTimeField(auto_now_add=True,)
    dateDue = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True, editable=True)
    dateCompleted = models.DateTimeField(auto_now=False, auto_now_add=False, null=True, blank=True, editable=True)
    completed = models.BooleanField(default = False)
    createdBy = models.CharField(max_length=35,blank=True,)
    completedBy = models.CharField(max_length=35,blank=True,)


    def __str__(self):
        return str(self.maintenanceItem)
    def get_absolute_url(self): 
        return reverse('equipmentdashboard',)


def check_complete(sender, instance,**kwargs):
    hasCompleteDate = instance.dateCompleted
    if not (hasCompleteDate is None):
        return
    else:
        isComplete = instance.completed
        if isComplete == True:
            completed_By = ?
            Maintenance.objects.filter(id = instance.id).update(completed = True, dateCompleted = timezone.now(), completedBy = completed_By,)


post_save.connect(check_complete, sender = Maintenance)
MattG
  • 1,682
  • 5
  • 25
  • 45
  • 3
    You have to do stuff related to the `request` object (the `user` is one of them) in your view. You can't use a model signal for that. To keep the logic with the model, just create a method on your model that takes the `user` as argument, but call that method from your view. – dirkgroten Aug 20 '19 at 11:02
  • 1
    Are you constrained to using signals? Alternatively, if you are using a form, pass in the user (from the view) as a form kwarg. Then when you call the `save()` method on the form, you can save the user to your model. – Daniel Holmes Aug 20 '19 at 11:07
  • 1
    https://lincolnloop.com/blog/django-anti-patterns-signals/ – bruno desthuilliers Aug 20 '19 at 11:31
  • Makes sense, thanks for the help guys. I was able to accomplish everything in the view as opposed to using signals. – MattG Aug 20 '19 at 15:49

0 Answers0