AttributeError: 'WSGIRequest' object has no attribute 'is_ajax'

I have included the following is_ajax() function, so that I can use it in another Django view function in the same views.py file.

def is_ajax(request):
return request.META.get(‘HTTP_X_REQUESTED_WITH’) == ‘XMLHttpRequest’

However, the problem is that I am still getting the following error message in the terminal:
AttributeError: ‘WSGIRequest’ object has no attribute ‘is_ajax’

The following image shows the views.py file where the is_ajax() function is being called on line 48:

I will appreciate any suggestions on how to resolve this issue. Thank you.

Your reference to is_ajax should be a local function call passing the request as a parameter, not trying to call the function on the request object.

if is_ajax(request):

When I attempt this, for some reason I get the following error in the terminal:
ValueError: Cannot assign “<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7f75e744f610>>”: “ExamResult.user” must be a “User” instance.

Image:

Why is this the case please?

Please copy/paste the traceback (not a screen image) you’re getting for this issue. The image you’ve pasted is for the object has no attribute error.

The following is the trackback when I click the “Save” button:

Django version 4.0.5, using settings 'django_project.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[]
Internal Server Error: /exams/2/save/
Traceback (most recent call last):
  File "/home/deniz/SeniorProject/django_project/vEnv/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
  File "/home/deniz/SeniorProject/django_project/vEnv/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/deniz/SeniorProject/django_project/Exams/views.py", line 96, in save_exam_view
    ExamResult.objects.create(exam=exam, user=user, score=score_)
  File "/home/deniz/SeniorProject/django_project/vEnv/venv/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/home/deniz/SeniorProject/django_project/vEnv/venv/lib/python3.8/site-packages/django/db/models/query.py", line 512, in create
    obj = self.model(**kwargs)
  File "/home/deniz/SeniorProject/django_project/vEnv/venv/lib/python3.8/site-packages/django/db/models/base.py", line 541, in __init__
    _setattr(self, field.name, rel_obj)
  File "/home/deniz/SeniorProject/django_project/vEnv/venv/lib/python3.8/site-packages/django/db/models/fields/related_descriptors.py", line 235, in __set__
    raise ValueError(
ValueError: Cannot assign "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7f8a12d34880>>": "ExamResult.user" must be a "User" instance.
[09/Jul/2022 23:39:58] "POST /exams/2/save/ HTTP/1.1" 500 91098

The following is how the “Save” button on the web page looks:
save

The general rule when looking at a traceback is to find the last reference to your code - that’s usually the best first place to start.

In this case, that reference is:

This area of the code is the cause of this error. So the next step would be for you to post your save_exam_view code.

Looking at this a bit closer, I see the error message is saying:

ValueError: Cannot assign “<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7f8a12d34880>>”: “ExamResult.user” must be a “User” instance.

It appears that this request is coming from an “unauthenticated” request. Is this user logged in? If not, then you don’t have a user object in the request. (Or more accurately, what you have is an instance of the AnonymousUser.)

Yes. Good news! I was able to fix the problem. I had to change the name of a variable that linked to one of the attributes for a particular model. I appreciate your help with all of this Mr. Whitesell.

@KenWhitesell I’m also facing same issue.

Error coming :
File “/home/kapil/Downloads/quiz-app-django-python/home/views.py”, line 37, in save_quiz_view

if request.is_ajax():
AttributeError: 'WSGIRequest' object has no attribute 'is_ajax'

Message: Coming While submitting.
[13/Oct/2022 10:49:59] “POST /2/save/ HTTP/1.1” 500 69421

My code file of views.py

def is_ajax(request):
    return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'

def save_quiz_view(request, myid):
    if request.is_ajax():  # Line 37 Error coming here.
        questions = []
        data = request.POST
        data_ = dict(data.lists())

        data_.pop('csrfmiddlewaretoken')

        for k in data_.keys():
            print('key: ', k)
            question = Question.objects.get(content=k)
            questions.append(question)

        user = request.user
        quiz = Quiz.objects.get(id=myid)

        score = 0
        marks = []
        correct_answer = None

        for q in questions:
            a_selected = request.POST.get(q.content)

            if a_selected != "":
                question_answers = Answer.objects.filter(question=q)
                for a in question_answers:
                    if a_selected == a.content:
                        if a.correct:
                            score += 1
                            correct_answer = a.content
                    else:
                        if a.correct:
                            correct_answer = a.content

                marks.append({str(q): {'correct_answer': correct_answer, 'answered': a_selected}})
            else:
                marks.append({str(q): 'not answered'})
     
        Marks_Of_User.objects.create(quiz=quiz, user=user, score=score)
        
        return JsonResponse({'passed': True, 'score': score, 'marks': marks})

I’m not able to submit.

This isn’t quite the same issue. The HttpRequest.is_ajax method was deprecated in Django 3.1 and removed in Django 4.0.

Are you actually trying to call the is_ajax method that you defined above your view? If so, then you don’t reference it as request.is_ajax, it’s just is_ajax.

1 Like

Thank you for your help.
It worked.

hello , how are you?
could you please tell me ?how you solve the problem ?
I have the same problem