尝试在Django中删除模型对象时出现错误

时间:2019-02-13 09:52:53

标签: python django django-models sqlite django-views


def employee_delete(request, id=None):
    user = get_object_or_404(User, id=id)
    #user = User.objects.get(id=id)
    if request.method == 'POST':
        print(type(user))
        self.user.delete()
        return HttpResponseRedirect(reverse('employee_list'))
    else:
        context = {}
        context['user'] = user
        return render(request, 'employee/delete.html', context)

在django 2.1.5中使用delete()删除对象时显示错误

Screenshot of the error

1 个答案:

答案 0 :(得分:1)

您正在创建基于功能的视图。因此请勿使用self

def employee_delete(request, id=None):
    user = get_object_or_404(User, id=id)
    #user = User.objects.get(id=id)
    if request.method == 'POST':
        print(type(user))
        user.delete() # change here
        return HttpResponseRedirect(reverse('employee_list'))
    else:
        context = {}
        context['user'] = user
        return render(request, 'employee/delete.html', context)

更新

在您的models.py中,您使用字符串CASCADE

user = models.OneToOneField(User, on_delete=models.CASCADE) # update like this