基于django类的删除视图和验证

时间:2015-06-10 04:25:18

标签: python django django-class-based-views

我的观点:

class ModEmailDeleteView(DetailView):
    model = EmailModel
    template_name = "email_delete.html"
    success_url = reverse_lazy('moderator_profile', request.user.id)

这里我想检查特定字段的用户是否是请求用户,然后才能删除。像

if obj.user == request.user

然后只有他可以删除或抛出404

如果我在url中有多个主键怎么办?并希望使用这些主键进行不同的验证

2 个答案:

答案 0 :(得分:1)

你可以这样做:

class ModEmailDeleteView(DeleteView):
    model = EmailModel
    template_name = "email_delete.html"
    success_url = reverse_lazy('moderator_profile', request.user.id)

    def delete(self, request, *args, **kwargs):
       self.object = self.get_object()
       if self.object.user == request.user:
          self.object.delete()
          return HttpResponseRedirect(self.get_success_url())
       else:
          raise Http404 #or return HttpResponse('404_url')

答案 1 :(得分:0)

  

django Deleview有mixin,你只需覆盖删除   功能在您的视图中,

class DeletionMixin(object):
"""
A mixin providing the ability to delete objects
"""
success_url = None

def delete(self, request, *args, **kwargs):
    """
    Calls the delete() method on the fetched object and then
    redirects to the success URL.
    """
    if self.object.user = request.user:
      self.object.delete()        
    success_url = self.get_success_url()
    self.object.delete()
    return HttpResponseRedirect(success_url)