2015-10-21 40 views
2

請看圖中,有一個2字段的表單。用戶輸入信息並提交表單後。該頁面將重定向到另一個html,顯示錶單和過濾的數據庫結果。django 1.8錯誤:'NoneType'對象不可調用

我的項目的結構是1模型與2類(inputform;結果),2 html和1 views.py。

現在的問題是「‘NoneType’對象不是可調用的。」所以,我懷疑這是因爲views.py,有什麼不對。你的幫助是非常讚賞。在此先感謝。

enter image description here

網址

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() 

回溯:

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 
205.   form = self.get_form() 
File "C:\Python27\lib\site-packages\django-1.8.3-py2.7.egg\django\views\generic\edit.py" in get_form 
74.   return form_class(**self.get_form_kwargs()) 
Exception Type: TypeError at /input/ 
Exception Value: 'NoneType' object is not callable 

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> 
{% endfor %} 
</div>  

<!--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.employee__sum}}</td> 

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

input.html

<div class="field"> 
     {{ form.company.errors }} 
     <label for="{{ form.company.id_for_label }}">Company:</label> 
     {{ form.company }} 
</div> 

<div class="field" > 
<label> Select the Region: 
    {{ form.region }} 
     {% for region in form.region.choices %} 
     <option value="region" name= "region" id="id_region">{{region}} </option> 
     {% endfor %} 
</label> 
</div> 

升級views.py根據建議

from result.forms import InputForm 
from django.views.generic import DetailView 
from django.views.generic.edit import FormView,FormMixin 
from django.contrib import messages 
from django.template import RequestContext 
from django.shortcuts import redirect 
from django.db.models import Sum,Avg 
from django.views.generic.detail import MultipleObjectMixin 

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 get(self, request, *args, **kwargs): 
     view = DupontView.as_view() 
     return view(request, *args, **kwargs) 

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

     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 super(ResultView,self).form_valid(form) 

    def get_success_url(self): 
     return reverse('dupont', kwargs={'pk': self.object.pk}) 

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


    <----how can I get the submitted information and query result here from InputFormView? Is following correct?---> 

    def get(self, request, *args, **kwargs): 
     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): 
     return self.object. ? .all() <---what to put here? are they "sales","departments","employee" from database filtered result together with the form data-"region" and "company"? 
+0

請問您可以包括完整的追溯? – ojii

+0

你可以發佈result_list.html,看起來有點腥! –

+0

它不存在,你給錯了鏈接!只是在這裏發佈! –

回答

2

請看看這些文件,也許它們會對你有所幫助。 https://github.com/EchoUA/Tweaks-and-Hacks/tree/master/miaomiao

+0

嗨@EchoUA團隊,真的非常感謝你,這真的很有用~~~,但是這個代碼仍然返回「XX缺少查詢集」的錯誤,如鏈接所示:http://stackoverflow.com/questions/33251737/django-1-8-xview-is-missing-a-queryset-define-xview- model-xview-queryset,solarissmoke暗示我們不應該在get_query方法中渲染模板,我仍然在考慮如何讓代碼運行 –

+0

Hi @EchoUA Team,我也有疑問,爲什麼不把表單放在裏面。清空數據...這些表單處理代碼在「類InputFormView」,而不是「類ResultView」? –

+0

你可以請完整的追溯? – EchoUA

1

在views.py中,上下文是一個字典!

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


<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> 
+0

嗨@Manjunath Satyamurthy,非常感謝,升級爲你建議,「ResultView缺少一個QuerySet是錯誤的。定義ResultView.model,ResultView.queryset或重寫ResultView.get_queryset()。「在我的視圖中是否有其他錯誤? –

1

你正在爲一個簡單的表單寫太多的代碼。

創建一個簡單的表單;這僅僅是你的第二個視圖中進行搜索:

class SearchForm(forms.Form): 
    company = forms.CharField() 
    region = forms.CharField() 

創建一個視圖來顯示錶單:

def search_form(request): 
    form = SearchForm(request.GET) 
    if form.is_valid(): 
     company = form.cleaned_data['company'] 
     region = form.cleaned_data['region'] 
     url = '{}?company={}&region={}'.format(reverse('result-list'), company, region) 
     return redirect(url) 
    return render(request, 'form.html', {'form': form}) 

創建一個視圖來顯示結果:

def show_results(request): 
    company = request.GET.get('company') 
    region = request.GET.get('region') 
    if company is None or region is None: 
     return redirect('input') 

    # Your normal logic here 
    queryset=Result.objects.filter(company=company,region=region) 
    sales=Result.objects.aggregate(Sum('sales')) 
    employee=Result.objects.aggregate(Sum('employee')) 
    departments=Result.objects.aggregate(Sum('departments')) 

    return render(request, 'results.html', {'sales': sales, 
              'employee': employee, 
              'departments': departments, 
              'queryset': queryset})    
+0

Hi @ Burhan Khalid,我喜歡你的簡單代碼,但是現在在提交表單後,它可以重定向到結果頁面,但它沒有顯示任何形式(提交的數據)和表格(過濾結果)。我的result_list.html有什麼不對嗎? –

1

如果我沒有理解正確地,當您發送GET請求到

127.0.0.1:8000/input/ 

然後你得到錯誤。當您向該網址發送發佈請求時,是否會收到同樣的錯誤?嘗試將input.html更改爲:

<div class="field"> 
    <!-- Check if the errors exist first before calling them. 
     If youre sending a GET request, then form errors will 
     probably not exist. --> 
     {% if form.company.errors %} 
      {{ form.company.errors }} 
      <label for="{{ form.company.id_for_label }}">Company:</label> 
     {% endif %} 
     {{ form.company }} 
</div> 

<div class="field" > 
<label> Select the Region: 
    {{ form.region }} 
     <!-- over here, are you sure form.region.choices exists? Can you 
      post your model/model form so that we can verify that 
      form.region.choices exists? --> 
     {% for region in form.region.choices %} 
     <option value="region" name= "region" id="id_region">{{region}} </option> 
     {% endfor %} 
</label> 
</div> 

讓我知道如果使用此代碼後仍然出現錯誤。在上面的代碼中,我留下了一個提及的註釋來驗證form.region.choices的存在。你可以上傳你的模型和模型表單,以便我們可以驗證form.region.choices是否存在?

+0

hi @ user2719875,非常感謝您,您的代碼有效,並且模型對您的筆記非常感興趣。我檢查了上述所有答案,但在重定向到未能顯示錶單數據的結果頁面時,存在所有問題。所以我想我會學習Ajax來解決問題。 –

相關問題