2016-11-14 125 views
0

我遇到了让Ajax与我的django视图一起工作的问题。确切的错误是Django视图没有返回HttpResponse对象

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 
        }); 
       }); 
      }); 

所有帮助,真是不胜感激谢谢增益

回答

2

return f(request, *args, **kwargs)在装饰器的包装器中调用视图函数。但是,只有ajax请求的分支才会执行print ,离开该功能没有return声明回报有效的响应对象:

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

所以,即使我要求的jQuery/AJAX没有重新加载页面,Django的还是需要做一回呈现模板? – crzyone9584

+0

每个请求必须有一个有效的回应。没有一个不是有效的回应。 –

+0

感谢您的解释和您的时间。它现在正在工作。 – crzyone9584

相关问题