crzyone9584 crzyone9584 - 18 days ago 6
Python Question

Django view didn't return an HttpResponse object

I'm having an issue with getting ajax to work with my django view. The exact error is


CustomMembers.decorators.formquestioninfo
didn't return an
HttpResponse
object. It returned
None
instead.


The view is limited by a custom decorator which is the following.

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


The view right now only contains a return to show the template along with a check if ajax was used to post a request.

View

@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


The ajax code that is being executes is: (the getCookie is based off of django documentation - 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
});
});
});


All help is really appreciated. Thanks gain.

Answer

return f(request, *args, **kwargs) calls the view function in the wrapper of the decorator. However, the branch for ajax requests only does a print and leaves the function without a return statement that returns a valid response object:

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