必须使用对象pk或slug调用通用详细信息viewResult

时间:2015-10-22 12:26:19

标签: django

我将此错误显示为标题。根据文件,我添加了" slug_url_kwarg ='结果'",(结果是应用名称)。它不起作用,然后我添加" def get_object(self):",它返回错误为" id是一个KeyError"

  1. 它自己创建的数据库是主要的:" id",所以我使用了这个" id"作为slug_field。这是对的吗?

  2. 您认为我是否有必要使用UpdateView?我希望html在提交表单后显示结果(使用ajax)?

  3. 事先准备好你的回复。

    网址

    url(r'^result_list/$',ResultView.as_view(),name='result'),
    

    views.py

    class ResultView(UpdateView):
        context_object_name = 'result_list'
        template_name = 'result_list.html'
        form_class = InputForm
        slug_field = 'result.id' ---here means the pk,right?
        slug_url_kwarg = 'result'
    
    
    
        def get_queryset(self):
            return Result.objects.all()
    
        def post(self, request, *args, **kwargs):
            form = InputForm(request.POST)
            if form.is_valid():
                if self.request.is_ajax():
                    company = form.cleaned_data['company']
                    region = form.cleaned_data['region']
    
                    queryset=Result.objects.filter(region=region)
                    return HttpResponse(simplejson.dumps(to_json),mimetype='application/json')
            else:
                 return HttpResponse(form.errors)
    
        def get_context_data(self, **kwargs):
            context = super(ResultView, self).get_context_data(**kwargs)
            context["sales"] = self.get_queryset().aggregate(Sum('sales'))
    
        def get_object(self):
            object = get_object_or_404(Result,id=self.kwargs['id'])  <!here is not correct--->
            return object
    

    回溯

    File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\core\handlers\base.py" in get_response
      132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
    File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\views\generic\base.py" in view
      71.             return self.dispatch(request, *args, **kwargs)
    File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\views\generic\base.py" in dispatch
      89.         return handler(request, *args, **kwargs)
    File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\views\generic\edit.py" in get
      267.         self.object = self.get_object()
    File "C:\Users\user\Desktop\project\result\views.py" in get_object
      54.         object = get_object_or_404(Result,id=self.kwargs['id'])
    
    Exception Type: KeyError at /result_list/
    Exception Value: 'id'
    

1 个答案:

答案 0 :(得分:3)

你忘了映射网址格式,你不需要在你的情况下指定slug_field和slug_url_kwarg:

url(r'^dupont_list/(?P<pk>[0-9]+)/$', DupontView.as_view(), name='dupont'),