我写了编辑和删除视图,他们工作。但我很快意识到任何人都可以编辑和删除任何帖子。我只希望创建帖子的用户能够删除和编辑帖子。
class PostUpdateView(UpdateView):
model = Post
form_class = PostForm
template_name = 'main/edit.html'
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.save()
return HttpResponseRedirect(self.object.get_absolute_url())
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(PostUpdateView, self).dispatch(request, *args, **kwargs)
class PostDeleteView(DeleteView):
model = Post
def get_success_url(self):
return "/"
@method_decorator(login_required)
def dispatch(self, request, *args, **kwargs):
return super(PostDeleteView, self).dispatch(request, *args, **kwargs)
答案 0 :(得分:0)
您可以覆盖视图的get_queryset
方法,并过滤查询集,以便只包含属于该用户的对象。例如,对于您的更新视图,您可以执行以下操作:
class PostUpdateView(UpdateView):
def get_queryset(self):
queryset = super(PostUpdateView, self).get_queryset()
return queryset.filter(user=self.request.user)