python – Django – redirecting back to a page shows http response (Json data) and not rendering-ThrowExceptions

Exception or error:

Question: What would be the best way of dealing with this so that the json response isn’t shown if the user redirects like this? Or to take the user back to the state of the quiz before the data is retrieved?

Bit of an awkward one to explain. I’m creating a quiz application using django. A user can select a quiz to undertake, when they select what quiz they are taken to the following page:
(Screenshot 1)
Quiz Start

When the quiz is started, an ajax request is sent to the back end to retrieve the questions for the quiz and display them to the user. The problem is if the quiz is already started and I use the browsers back button and then reload the page it shows the json response instead of (Screenshot 1) it shows:

Json Response:

Json

View.py

def active_quiz(request, quiz_pk):
    quiz = Quiz.objects.filter(pk=quiz_pk)

    questions = Questions.objects.filter(quiz=quiz_pk)

    if request.is_ajax():
        if request.method =="GET":
            serial = serializers.serialize("json", Questions.objects.filter(quiz=quiz_pk))

            response_data = serial
            return HttpResponse(response_data, content_type="application/json")

    args={'question': questions, 'quiz': quiz}
    return render(request, 'quiz/quiz_active.html', args
How to solve:

I know this is probably not the answer you are expecting but you should split your views, and create two different endpoints for API and rendering purpose.

Also, can you take a look at this ?

request.is_ajax() == True when clicking back button?

###

I’d suggest to use JsonResponse instead of HttpResponse. It’ll go to your ajax.

return JsonResponse(json_object, safe=False)

Leave a Reply

Your email address will not be published. Required fields are marked *