django 1.8:XView缺少QuerySet。定义XView.model,XView.queryset,

时间:2015-10-21 05:42:06

标签: python django database

转到网址时收到错误:/result_list.html。但是在views.py中确实存在查询集,那么可能是其他原因呢?提前致谢。该函数基于用户提交的表单,然后过滤数据库并在result_list.html中显示表单条目和数据库结果。

回溯

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\list.py" in get
159.         self.object_list = self.get_queryset()
File "C:\Users\user\Desktop\SCOR\result\views.py" in get_queryset
70.         return super(ResultView,self).get_queryset()

get_queryset中的文件“C:\ Python27 \ lib \ site-packages \ django-1.8.3-py2.7.egg \ django \ views \ generic \ list.py”     44.'cls':self。 class 名称
    异常类型:在/ result_list /中配置不正确     异常值:ResultView缺少QuerySet。定义ResultView.model,ResultView.queryset或覆盖ResultView.get_queryset()。

以下是摘录:

网址

from result.views import ResultView,InputFormView
from django.views.generic import TemplateView,FormView,ListView

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

views.py

from result.forms import InputForm
from result.models import Result,Input
from django.views.generic.list import ListView
from django.views.generic import FormView
....

@csrf_exempt

class InputFormView(FormView):
    template_name = 'inputform.html'
    form = InputForm

    def get_success_url(self):  /*redirect to result page with submitted form information*/
        return ''.join(
            [
                reverse('dupont'),
                '?company=',self.request.POST.get('company'),
                '?region=',self.request.POST.get('region')
            ]
        )

class ResultView(ListView):
    context_object_name = 'result_list'
    template_name = 'result_list.html'

    def get_context_data(self, **kwargs):
        context = super(ResultView, self).get_context_data(**kwargs)
        return context

    def get_queryset(self):
        if self.request.method == 'POST':
            form = InputForm(self.request.POST)
            if form.is_valid():
                company = form.cleaned_data['company']
                region = form.cleaned_data['region']

/---Based on form entry, do the filter on the database-----/

                queryset=Result.objects.filter(region=region,company=company)
                sales=Result.objects.filter(queryset).aggregate(Sum('sales'))
                employee=Result.objects.filter(queryset).aggregate(Sum('employee'))
                departments=Result.objects.filter(queryset).aggregate(Sum('departments'))

                form.save()

                return render(request,'result_list.html',{'company':company},{'region':region},{'employee':employee},{'sales':sales},{'departments':departments})

            else:
                print form.errors
        else:
            form=InputForm()                   
        return super(ResultView,self).get_queryset()

result_list.html

<div class="basicinfo">         <!--Entry Form information submitted by user-->

    <table border="1" cellpadding="1">
    <tr>
        <td align="left">Company</td>
        <td>{{company}}</td>
    </tr>
    <tr>
        <td align="left">Region</td>
        <td>{{region}}</td>
    </tr>
  </table>

<!--Showing the filtered result in database-->  
<td><table border="0" cellspacing="10" cellpadding="10">
<tr><b>Sales</b></tr>
<td bgcolor="#F0F0F0"> {{sales}}</td>

</tr>
<tr><b>Employee</b></tr>
<tr>
<td bgcolor="#F0F0F0"> {{employee}}</td>

</tr>
<tr><b>Departments</b></tr>
<td bgcolor="#F0F0F0"> {{departments}}</td>
</td></table>

版本2.0 views.py根据solarissmoke'和pythad的建议

class InputFormView(FormMixin,DetailView):
    template_name = 'inputform.html'
    form = InputForm

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        form=self.get_form()
        if form.is_valid():
            return self.form_valid(form)
        else:
            return self.form_invalid(form)
            print form.errors

    def form_valid(self, form):
        company = form.cleaned_data['company']
        region = form.cleaned_data['region']

        return super(ResultView,self).form_valid(form) 《Q1:---If here to return to ResultView or InputFormView?--->

    def get_success_url(self):   #Redirect to result_list.html
        return reverse('result', kwargs={'pk': self.object.pk})


class ResultView(MultipleObjectMixin,DetailView):
    context_object_name = 'result_list'
    template_name = 'result_list.html'

    <---Q2: How can I get the form data entry from InputFormView?-->

    def get(self, request, *args, **kwargs):
        view = InputFormView.as_view()
        self.object = self.get_object(queryset=Result.objects.filter(company=company,region=region))            
        return super(Result, self).get(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        context = super(ResultView, self).get_context_data(**kwargs)
        context['InputFormView']= self.object
        return context


    def get_queryset(self):

<--Error!-- this sentence is where reports error as "global name company,region not defined"-->

        queryset=Result.objects.filter(company=company,region=region)
        sales=Result.objects.queryset.aggregate(Sum('sales'))
        employee=Result.objects.queryset.aggregate(Sum('employee'))
        departments=Result.objects.queryset.aggregate(Sum('departments'))

        return self.object.all()  

1 个答案:

答案 0 :(得分:3)

您的代码存在多个问题:

  1. 您的if self.request.method == 'POST':方法中有get_queryset个阻止。如果计算结果为False,则回退到父get_queryset方法,这是触发错误的方法(因为父方法需要给出模型或查询集,如错误中所示)。因此,如果您尝试向result_list/发送简单的GET请求,则会失败,因为ListView没有查询集。

  2. 您不应该在get_queryset方法内渲染模板。该方法应返回一个查询集,而不是其他任何东西。这将失败。

  3. 您的ResultView确实不应该首先处理POSTed表单数据。您应该在FormView中处理该问题,然后使用FormView success_url参数将用户重定向到相应的结果视图,如documentation on form processing中所述。