2012-08-04 71 views
0

我面臨這個異常錯誤,我對此感到困惑,因爲這個方法在類似的系統中工作,感謝任何幫助或指針。非常感謝!Django - view沒有返回HttpResponse對象

異常值:該視圖Project.qna.views.add_vote未返回HttpResponse對象。

def add_vote(request): 

if request.method == "POST": 
    q_id = request.POST['vote_form_q_id'] 
    a_id = request.POST['vote_form_a_id'] 
    vote_value = request.POST['vote_form_value'] 

    ok = False 
    vote_num = None 
    name = None 

    if q_id: 
     try: 
      question = Question.objects.get(id=q_id) 
      question.num_vote += int(vote_value) 
      question.save() 
      vote_num = question.num_vote 
      name = 'Question_'+str(q_id) 
      ok = True 

     except Question.DoesNotExist: 
      pass 
    elif a_id: 
     try: 
      answer = Answer.objects.get(id=a_id) 
      answer.num_vote += int(vote_value) 
      answer.save() 
      vote_num = answer.num_vote 
      name = 'Answer_'+str(a_id) 
      ok = True 
     except Answer.DoesNotExist: 
      pass 

    if ok and request.is_ajax: 
     result = simplejson.dumps({ 
      "vote_num": vote_num, 
     }, cls=LazyEncoder) 
     response = HttpResponse(result, mimetype='application/javascript') 

     response.set_cookie(name, datetime.now) 
    return response 
+0

嘛。如果您的縮進在實際文件中是相同的,那麼它將無法工作,因爲這是一個錯誤的開始。 – aychedee 2012-08-04 10:43:48

+1

提示:當你最後一個「if」失敗時會發生什麼? – 2012-08-04 13:30:18

回答

0

請修復您的注意事項,您似乎也有很多可以簡化的解決方法。

每個django視圖都應該返回一個HttpResponse對象,你似乎有很多地方不會這樣。爲了縮小您的問題範圍,請將pass更改爲print聲明以查看代碼實際失敗的位置。如果您可以展示您的POST數據,這將非常有幫助。

0

那麼很難說沒有看到你對視圖做出什麼樣的要求。但是你發送POST請求嗎?因爲您不以任何方式處理GET請求。此外,縮進也是錯誤的。但那可能只是切割和粘貼出錯。

0

這是未經測試,但它是一個更清潔,更可靠的設計,我相信你的邏輯在配合和突出的點,回訪的HttpResponse是必要的:

def add_vote(request): 
    if not (request.method == 'POST' and request.is_ajax): 
     return # Some suitable response here 
    try: 
     vote_value = int(request.POST.get('vote_form_value','')) 
    except ValueError as e: 
     pass # Some suitable response here 

    def saveobj(model, key, val): # helper function to reduce code repetition 
     item = model.objects.get(id=key) 
     item.num_vote += val 
     item.save() 
     return item.num_vote, '%s_%s' % (model.__class__.__name__, key) 

    for model, key in [(Question, 'vote_form_q_id'), (Answer, 'vote_form_a_id')]): 
     try: 
      new_vote_value, name = saveobj(model, request.POST[key], vote_value) 
      break 
     except (KeyError, ObjectDoesNotExist) as e: 
      continue # or error out 
    else: 
     pass # neither question or answer found - so suitable response here 

    # return ajax response here.... 
相關問題