Django4: Ajax AttributeError

Question:

I’m trying to create this Ajax request:
The views file is as follows:

reports/views.py

from django.shortcuts import render
from profiles.models import Profile
from django.http import JsonResponse
from .utils import get_report_image
from .models import Report
from .forms import ReportForm
# Create your views here.

def create_report_view(request):
    form = ReportForm(request.POST or None)
    if request.is_ajax():
        image = request.POST.get('image')
        name = request.POST.get('name')
        remarks = request.POST.get('remarks')
        img = get_report_image(image)
        author = Profile.objects.get(user=request.user)
        
        if form.is_valid():
            instance = form.save(commit=False)
            instance.image = img
            instance.author = author
            instance.save()
        #   Report.objects.create(name=name, remarks=remarks, image=img, author=author)
        
        return JsonResponse({'msg': 'send'})
    return JsonResponse({})

utils.py

import base64, uuid
from django.core.files.base import ContentFile

def get_report_image(data):
    _ , str_image = data.split(';base64')
    decoded_img = base64.b64decode(str_image)
    img_name = str(uuid.uuid4())[:10] + '.png'
    data = ContentFile(decoded_img, name=img_name)
    return data

urls.py

from django.urls import path
from .views import create_report_view

app_name = 'reports'

urlpatterns = [
    path('save/', create_report_view, name='create-report'),
]

forms.py

from django import forms
from .models import Report

class ReportForm(forms.ModelForm):
    class Meta:
        model = Report
        fields = ('name', 'remarks')

I’m not sure why but this is the error I’m getting. Does this mean that is_ajax() is no longer accepted with Django 4.1.1? If so how would I need to adjust the code?

if request.is_ajax():
AttributeError: 'WSGIRequest' object has no attribute 'is_ajax'
[21/Sep/2022 07:23:39] "POST /reports/save/ HTTP/1.1" 500 98007
Asked By: a56z

||

Answers:

here is a way to implement is_ajax to every request:

  1. create a middlewares.py in any of your app, in my case, common app. (it does not matter which app you add this in, middlewares are wrapper functions called globally to perform action before or after view).

class AjaxMiddleware:
def init(self, get_response):
self.get_response = get_response

    def __call__(self, request):
        def is_ajax(self):
            return request.META.get('HTTP_X_REQUESTED_WITH') == 
                   'XMLHttpRequest'
        
        request.is_ajax = is_ajax.__get__(request)
        response = self.get_response(request)
        return response

this will define a is_ajax method on every request before it is received by the view.

  1. plug this in settings.py:

    MIDDLEWARE = [
    ‘common.middleware.AjaxMiddleware’,
    ]

And this will solve your error.

Answered By: Manoj Tolagekar

Ok, seems to be working now. request.is_ajax is deprecated since django 3.1 and has been removed since django 4

if request.headers.get('x-requested-with') == 'XMLHttpRequest': 

instead of

if request.is_ajax:
Answered By: a56z
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.