ajknzhol
ajknzhol

Reputation: 6450

How to assign the User object to save method in Django

I am trying to log the activities during save operation to track all the changes to user model. my approach is as follows.

class User(AbstractUser):
    undergrad_college = models.CharField(max_length=20, choices=COLLEGE_CHOICES)
    undergrad_degree = models.CharField(max_length=20, choices=COLLEGE_DEGREES)
    postgrad_college = models.CharField(max_length=20, choices=COLLEGE_CHOICES)
    postgrad_degree = models.CharField(max_length=20, choices=COLLEGE_DEGREES)
    currently_working_on = models.TextField()
    previous_work_experience = models.TextField()
    previous_internship_experience = models.TextField()

    def __str__(self):
        return self.username

    def save(self, *args, **kwargs):
        Log(user=User, actions="Updated profile",
            extra={"undergrad_college": self.undergrad_college,
                   "undergrad_degree": self.undergrad_degree,
                   "postgrad_college": self.postgrad_college,
                   "postgrad_degree": self.postgrad_degree,
                   "currently_working_on": self.currently_working_on,
                   "previous_work_experience": self.previous_work_experience,
                   "previous_internship_experience": self.previous_internship_experience
            })
        super(User, self).save(args, **kwargs)

my views are like this for handling the logging.

class ActivityMixin(LoginRequiredMixin):
    def get_context_data(self, **kwargs):
        context = super(ActivityMixin, self).get_context_data(**kwargs)
        context['activities'] = Log.objects.filter(user=self.request.user)
        return context


class IndexListView(ActivityMixin, ListView):
    template_name = 'pages/home.html'
    model = User

I get this error while performing the update action.

Cannot assign "<class 'users.models.User'>": "Log.user" must be a "User" instance.

Update view is as follows

class UserUpdateView(LoginRequiredMixin, UpdateView):
    form_class = UserForm

    # we already imported User in the view code above, remember?
    model = User

    # send the user back to their own page after a successful update
    def get_success_url(self):
        return reverse("users:detail",
                       kwargs={"username": self.request.user.username})

    def get_object(self, **kwargs):
        # Only get the User record for the user making the request
        return User.objects.get(username=self.request.user.username)

How to assign the User model instance to the Log function. I cant get this working. I am Django newbie.

Upvotes: 0

Views: 403

Answers (1)

madzohan
madzohan

Reputation: 11808

Looks like pretty straightforward, replace User with self:

Log(user=User, ...

Log(user=self, ...

Upvotes: 1

Related Questions