Django - view没有返回一个HttpResponse对象

时间:2012-08-04 10:39:06

标签: python django

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

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

3 个答案:

答案 0 :(得分:0)

请修复您的缩进,您似乎还有很多可以简化的解决方法。

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

答案 1 :(得分:0)

如果没有看到你对视图提出了什么样的要求,那么很难说清楚。但是你发送了POST请求吗?因为您不以任何方式处理GET请求。缩进也是错误的。但这可能只是切割和粘贴出了问题。

答案 2 :(得分: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....