Django仅为所有者删除和更新视图

时间:2018-04-20 11:24:37

标签: python django django-views

我在Django为我的大学写了一些任务。在我的更新和删除视图中,我想确保只有对象的所有者才能更新/删除它。现在每个人都可以做到。

以下是观点:

class UpdateCar(SuccessMessageMixin, UpdateView):
    model = Car
    form_class = AddNewCarForm
    template_name = 'c2crental/car/update_car.html'
    success_url = reverse_lazy('c2crental:list_user_cars')
    success_message = _("Car has been updated.")

    def get_queryset(self):
        owner = self.request.user
        return self.model.objects.filter(owner=owner)


class DeleteCar(DeleteView):
    model = Car
    success_url = reverse_lazy('c2crental:list_user_cars')
    template_name = 'c2crental/car/delete_confirm_car.html'
    success_message = _("Car has been deleted.")

    def delete(self, request, *args, **kwargs):
        messages.success(self.request, self.success_message)
        return super(DeleteCar, self).delete(request, *args, **kwargs)

    def get_queryset(self):
        owner = self.request.user
        return self.model.objects.filter(owner=owner)

我找到了一些带有查询集的解决方案,如上所示。他们不会让其他用户更新/删除对象并引发Http404错误,这很好,但我想使用Django消息框架在页面上打印错误消息,不要重定向到Http404页面。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

您可以通过覆盖视图中的dispatchget_object方法来完成此操作。

正如您所见,如果get_object找不到对象,则会抛出404,所以如果您不匹配所有者,则可以投掷403或404

def get_object(self, queryset=None):
    """
    Check the logged in user is the owner of the object or 404
    """
    obj = super(MyView, self).get_object(queryset)
    if obj.owner != self.request.user:
        raise Http404(
            _("You don't own this object")
        )
    return obj