Home > Net >  Tried to update field with a model instance, <SimpleLazyObject:<<>>. Use a value comp
Tried to update field with a model instance, <SimpleLazyObject:<<>>. Use a value comp

Time:02-10

I am trying to over ride the save method in my model to store the currently loged in user. I am using the django-current user to get the authenticated user. I wrote this code

from django_currentuser.middleware import (
    get_current_user, get_current_authenticated_user)

from django_currentuser.db.models import CurrentUserField

 uploaded_by = models.CharField(max_length=255, blank=True, null=True, editable=False)

 def save(self, *args, **kwargs):

     user = get_current_authenticated_user()

     self.uploaded_by = user

     super(Citation, self).save(*args, **kwargs)
   

But I am getting this error

Tried to update field professional.Citation.uploaded_by with a model instance, <SimpleLazyObject: <CustomUser: [email protected]>>. Use a value compatible with CharField.

What should I do? I want to store the currently logged in user in the model save method and also keep this field non editable.

I am getting this error only when the field is being updated. It is working fine wile saving for the first time

CodePudding user response:

Your are getting this error because you are trying to save user object in an char field. Your uploaded_by filed is an CharField. You can save only string value in this fields.

try this and hope this will solved your problems:

 from django.contrib.auth.models import User #import user model
 # add user ForeignKey fields in your model
 user = models.ForeignKey(User,on_delete=models.CASCADE) 
 uploaded_by = models.CharField(max_length=255, blank=True, null=True, editable=False)
   

    def save(self, *args, **kwargs):
    
         user = self.user.username

         if not self.uploaded_by:
             self.uploaded_by = user
    
         super(Citation, self).save(*args, **kwargs)

CodePudding user response:

This is how I overcame the error

def save(self, *args, **kwargs):

        current_user = get_current_authenticated_user()
        
        user =CustomUser.objects.get(email = current_user)

        self.uploaded_by = user.email

        super(Citation, self).save(*args, **kwargs)
   

Here I am getting the user before directly saving it using get_current_authenticated_user() and then I am storing the user name (in my case email).

  • Related