The view didn't return an HttpResponse object. It returned None instead

i am trying to create a function to save favourite post to users profile, this is working fine in the database it adds and removes the favourite post but when the view is called it shows this error The view didn’t return an HttpResponse object. It returned None instead.

def save(request, book_slug):
    user = request.user 
    book = Book.objects.get(slug=book_slug)
    post = get_object_or_404(Book, slug=request.POST.get('post_slug'))
    profile = Profile.objects.get(user=user)
    is_saved = False 
    if profile.favourite_book.filter(slug=book_slug).exists():
        is_saved = False 
        is_saved = True 

    context = {
    if request.is_ajax():
        html = render_to_string('books/save_section.html', context, request=request)
        return JsonResponse({'form': html})

First, a side note: The is_ajax method is deprecated. (See You want to remove that call and identify an appropriate replacement (if necessary).

Now, to the issue you’re raising, if is_ajax() is returning false, then your render and return statement aren’t running - the function “falls out the bottom” and doesn’t return a value. That’s the cause of the error.

1 Like

Thanks for your response, so in this is case please can you guide me on what to do, i am kinda lost now?

So the easiest initial step, based only what you are showing here, is to remove the if is_ajax() condition and un-indent the two statements in that condition such that those statements always execute.

If you’re calling this view from both an AJAX call and a normal HTTP request, then I’m going to need to see more details about how this view is being called.

1 Like

that was it, i removed the is_ajax() and unindented the two statements, thanks