【问题标题】:Django view didn't return an HttpResponse objectDjango 视图没有返回 HttpResponse 对象
【发布时间】:2017-03-28 09:33:29
【问题描述】:

我在让 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
                    });
                });
            });

非常感谢所有帮助。感谢收获。

【问题讨论】:

    标签: python ajax django


    【解决方案1】:

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

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

    【讨论】:

    • 所以即使我要求 jquery/ajax 不要重新加载页面,django 仍然需要返回来渲染模板?
    • 每个请求都必须得到有效响应。 None 不是有效的响应。
    • 感谢您的解释和您的时间。它现在正在工作。
    • @MosesKoledoye,我可以请你看一下这里的相关问题吗:stackoverflow.com/questions/50671066/…
    猜你喜欢
    • 2011-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多