本文介绍了/ sss / edit /'pk'上的KeyError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
你好我收到这个错误:/ sss / edit /
'pk'
的KeyError我知道keyError意味着在dict中没有键。但我不明白为什么它给我。它看起来很简单,但我得到这个错误。这是我的代码
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,请求,* args,** kwargs):
post = Post.objects.get(pk = kwargs ['pk'])
如果request.user.has_perm('main.change_post')和帖子.created_by == request.user:
return super(PostUpdateView,self).dispatch(request,* args,** kwargs)
else:
返回http.HttpForbidden()
我从 post = Post.objects.get(pk = kwargs ['pk '])
我的这个模型是w
class Post(models.Model):
pub_date = models.DateTimeField(auto_now_add = True)
感谢高级
解决方案
如果您已经在urls.py中定义了这个,您只能访问 pk
:
url(r'^ sss / edit /(?P< pk> \d +)$',PostUpdateView.as_view())
/ pre>
Hello I get this error:KeyError at /sss/edit/ 'pk' I know keyError mean there's no key in a dict. but I don't understand why it's giving me. It looks so simple but I get this error. Here's my code
class PostUpdateView(UpdateView): model = Post form_class = PostForm template_name = 'main/edit.html' def form_valid(self, form): self.object = form.save(commit=False) # Any manual settings go here self.object.save() return HttpResponseRedirect(self.object.get_absolute_url()) @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): post = Post.objects.get(pk=kwargs['pk']) if request.user.has_perm('main.change_post') and post.created_by == request.user: return super(PostUpdateView, self).dispatch(request, *args, **kwargs) else: return http.HttpForbidden()
I get error from
post=Post.objects.get(pk=kwargs['pk'])
I have this model as well
class Post(models.Model): pub_date = models.DateTimeField(auto_now_add = True)
thanks in advanced
解决方案You can only access the
pk
if you have defined it in your urls.py like this:url(r'^sss/edit/(?P<pk>\d+)$', PostUpdateView.as_view())
这篇关于/ sss / edit /'pk'上的KeyError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!