我希望能够编辑帖子并保存。
到目前为止,我已设法执行此操作以及检查用户是否已登录。
但是,我似乎无法确定如何验证用户是否有权这样做。
这是我的代码:
class PostUpdate(UpdateView):
model = Post
fields = ['title','body','page','category']
template_name = 'post_update.html'
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(PostUpdate, self).dispatch(*args, **kwargs)
def form_valid(self, form):
form.instance.owner_user = self.request.user
return super(PostUpdate, self).form_valid(form)
在我的Post模型中,我有一个名为" owner_user"将用户作为外键保存:
owner_user = models.ForeignKey(User)
我希望能够使用我在 urls.py
中的pk
变量
url(r'^post/(?P<pk>\d+)/edit',
PostUpdate.as_view(),
name='PostUpdate'),
并检查它是这样的:
post = get_object_or_404(Post,id=pk)
if post.owner_user == request.user:
#Show edit page
else:
return HttpResponseForbidden()
我怎样才能实现这个目标?
答案 0 :(得分:3)
添加一个get_object方法并检查用户是否是对象的所有者:
class PostUpdate(UpdateView):
model = Post
fields = ['title','body','page','category']
template_name = 'post_update.html'
@method_decorator(login_required)
def dispatch(self, *args, **kwargs):
return super(PostUpdate, self).dispatch(*args, **kwargs)
def get_object(self, *args, **kwargs):
obj = super(PostUpdate, self).get_object(*args, **kwargs)
if not obj.owner_user == self.request.user:
raise Http404
return obj
def form_valid(self, form):
form.instance.owner_user = self.request.user
return super(PostUpdate, self).form_valid(form)