“用户”对象没有属性“ soft_delete”-Django软删除

时间:2018-12-31 08:37:12

标签: django django-models django-forms django-templates django-views

我已经在我的项目中创建了软删除,并且工作正常。但是问题是我正在使用User内置模型,并且将OneToOneFieldUserProfile一起使用。现在soft_delete函数在UserProfile模型中,即时通讯使用generic.DeleteView删除用户。问题是我无法将User的对象传递给UserProfile来将user_is_deleted设置为True。这是我的代码。

Views.py

class UserDeleteView(LoginRequiredMixin, generic.DeleteView):
    model = User
    template_name = 'users/user_confirm_delete.html'
    success_url = '/users/'

    def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.object.soft_delete()
        return HttpResponseRedirect(self.get_success_url())

Models.py

class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    user_company = models.ForeignKey(Company, on_delete=models.CASCADE)
    user_role = models.ForeignKey(Roles, on_delete=models.CASCADE)
    user_is_deleted = models.BooleanField(default=False)
    user_deleted_at = models.DateTimeField(blank=True, null=True)

    def soft_delete(self):
        self.user_is_deleted = True
        self.user_deleted_at  = timezone.now() - tdelta(days=-1)
        self.save()

软删除参考-https://blog.khophi.co/soft-delete-django-quickly/

2 个答案:

答案 0 :(得分:2)

更改此

@classmethod
def soft_delete(self):
    ...

答案 1 :(得分:1)

将您的 delete() 方法更改为

def delete(self, request, *args, **kwargs):
    self.object = self.get_object()
    self.object.userprofile.soft_delete()
    return HttpResponseRedirect(self.get_success_url())