Home > database >  AttributeError at /Customer/Visit 'WSGIRequest' object has no attribute 'is_ajax'
AttributeError at /Customer/Visit 'WSGIRequest' object has no attribute 'is_ajax'

Time:01-30

Please Help me im trying to learn ajax in django but when i running this simple test i got this error and i cant find the reason, my django version is 4.0

error

AttributeError at /Customer/Visit

'WSGIRequest' object has no attribute 'is_ajax'

This is my js file code:

enter code here
const alertBox = document.getElementById('alert-box')
const imagebox = document.getElementById('image-box')
const form = document.getElementById('visit-form')

const customer = document.getElementById('id_Customer')
const visit_date = document.getElementById('id_Visit_date')
const price = document.getElementById('id_Price')
const pic = document.getElementById('id_Pic')

const csrf = document.getElementsByName('csrfmiddlewaretoken')

const url = ''

const handelAlert = (type, text) => {
    alertBox.innerHTML = '<div '   type   '"> '   text   ' </div>'
}

pic.addEventListener('change', () => {
    const image_data = pic.files[0]
       const url = URL.createObjectURL(image_data)
       console.log(url)
           imagebox.innerHTML = '<img src="'   url   '" width="50%" >'
})

form.addEventListener('submit', e => {
    e.preventDefault()

const fd = new FormData()
fd.append('csrfmiddlewaretoken', csrf[0].value)
fd.append('customer', customer.value)
fd.append('visit_date', visit_date.value)
fd.append('price', price.value)
fd.append('pic', pic.files[0])
alert('df')
$.ajax({
    type: "POST",
    url: url,
    enctype: 'multipart/form-data',
    data: fd,
    success: function(response) {
        console.log(response)
        const sText = 'ثبت '   response.visit_date   'با موفقیت انجام شد'
        handelAlert('success', sText)
        setTimeout(() => {
            alertBox.innerHTML = ""
            imagebox.innerHTML = ""
            customer.value = ""
            visit_date.value = ""
            price.value = ""
            pic.value = ""
        }, 2000)
    },
    error: function(error) {
        console.log(error)
        handelAlert('danger', 'خطا در ثبت')
    },
    cache: false,
    contentType: false,
    processType: false,
})

})
console.log(form)

This is my Html file code:

<div >
        <div id="alert-box"></div>

        <form id="visit-form" autocomplete="off">
            {% csrf_token %} {{ form|crispy }}

            <button type="submit" > ثبت ویزیت </button>

        </form>
        <div id="image-box"></div>
    </div>

This is my View.py file code:

def Visit(request):
    list_visit = VisitModel.objects.all()
    form = VisitForm(request.POST or None, request.FILES or None)
    data = {}
    if request.is_ajax():
        if form.is_valid():
            form.save()
    data['name'] = form.cleaned_data.get('name')
        data['status'] = 'ok'
        return HttpResponse(data)
context = {
    'form': form,
    'list_visit':list_visit
}
return render(request, 'customer/visit.html', context)

views

CodePudding user response:

HttpRequest.is_ajax() method is deprecated from Django 3.1 and also removed in Django 4.0 as documented

Instead you should can inspect Accept header as per cleanup ticket

If you still want replicate old method functionality you can make your own base on source

def is_ajax(request):
    return request.headers.get('x-requested-with') == 'XMLHttpRequest'

CodePudding user response:

In the new version of django is_ajax was removed. You can do it by self, using this code for example:


def is_ajax(request):
    if request.META.get("HTTP_X_REQUESTED_WITH") == "XMLHttpRequest":
        return True

    if request.content_type == "application/json":
        return True
    return False

CodePudding user response:

Which version of Django are you using?

From the release note of 3.1

The HttpRequest.is_ajax() method is deprecated as it relied on a jQuery-specific way of signifying AJAX calls, while current usage tends to use the JavaScript Fetch API. Depending on your use case, you can either write your own AJAX detection method, or use the new HttpRequest.accepts() method if your code depends on the client Accept HTTP header

If you want to write your own AJAX detection method then you can check the request as

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

If you are writing your own AJAX detection method, request.is_ajax() can be reproduced exactly as request.headers.get('x-requested-with') == 'XMLHttpRequest'

So you can create your custom method as

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

And use this method anywhere you want.

  •  Tags:  
  • Related