0

我正面临这个异常错误,我对此感到困惑,因为这种方法在类似的系统中工作,感谢任何帮助或指示。非常感谢!

异常值:视图 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
4

3 回答 3

0

请修正你的缩进,而且你似乎有很多可以简化的解决方法。

每个 django 视图都应该返回一个 HttpResponse 对象,您似乎有很多地方不是这种情况。为了缩小您的问题范围,将每个更改pass为一个print语句,以查看您的代码实际失败的位置。如果您可以展示您的 POST 数据,那将非常有帮助。

于 2012-08-04T10:45:04.940 回答
0

这是未经测试的,但它是一个更清洁、更健壮的设计,我相信它符合您的逻辑,并强调了返回 anHttpResponse是必要的点:

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....
于 2012-08-04T13:25:49.213 回答
0

好吧,如果不看到您对视图提出了什么样的请求,就很难判断。但是你是在发送 POST 请求吗?因为您不以任何方式处理 GET 请求。缩进也是错误的。但这可能只是剪切和粘贴出错了。

于 2012-08-04T10:45:23.083 回答