如何在Django中将User对象分配给save方法

时间:2014-12-14 07:20:24

标签: python django

我正在尝试在保存操作期间记录活动以跟踪对用户模型的所有更改。我的方法如下。

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)

我的观点就像处理日志记录一样。

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

执行更新操作时出现此错误。

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

更新视图如下

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)

如何将用户模型实例分配给日志功能。我不能让这个工作。我是Django新手。

1 个答案:

答案 0 :(得分:1)

看起来非常简单,将User替换为self

Log(user=User, ...

Log(user=self, ...