Django视图没有返回HttpResponse对象

时间:2016-11-14 16:56:15

标签: python ajax django

我遇到了让ajax与我的django视图一起工作的问题。确切的错误是

  

CustomMembers.decorators.formquestioninfo没有回复   HttpResponse对象。它改为None

视图受到自定义装饰器的限制,如下所示。

def is_god_admin(f):
    def wrap(request, *args, **kwargs):
        # This checks to see if the user is a god admin. If they are not, they get thrown to their profile page
        if 'userID' not in request.session.keys() and 'username' not in request.session.keys():
            return HttpResponseRedirect("/Members/Login")
        else:
            # lets check the roleID to what ID we need.
            god_admin = Roles.objects.get(role_name='System Admin')
            if request.session['roleID'] != god_admin.id:
                return HttpResponseRedirect("/Members/Profile/" + request.session['userID'])
            return f(request, *args, **kwargs)

    wrap.__doc__ = f.__doc__
    wrap.__name__ = f.__name__
    return wrap

现在的视图只包含一个返回以显示模板,同时检查ajax是否用于发布请求。

查看

@is_god_admin
def formquestionsinfo(request, formid, catid, mainid):
    """ Displays the forms information."""
    # need the following values in both post and get methods

    forms = Form.objects.all()

    if request.is_ajax():
        print('ajax request') # this fires then errors
    else:
        return render(request, formquestions.html, 'forms':forms) # this works just fine with a get request

正在执行的ajax代码是:( getCookie基于django文档 - Cross Site Request Forgery protection

$(document).ready(function(){
                $("#{{main_id}}_main_visible").click(function(e){
                    e.preventDefault();
                    var url = window.location.href;
                    $.ajax({
                      type:'get',
                      headers: {"X-CSRFToken": getCookie("csrftoken")},
                      url: url,
                      data: { mainid: {{main_id}} },
                      async: true,
                      cache: false
                    });
                });
            });

非常感谢所有帮助。谢谢你。

1 个答案:

答案 0 :(得分:2)

return f(request, *args, **kwargs)在装饰器的包装器中调用视图函数。但是,ajax请求的分支只执行print并且在没有{em>返回有效响应对象的return语句的情况下离开该函数:

if request.is_ajax():
    print('ajax request') 
    ... # return a response object here to avoid returning None