skip to Main Content

AttributeError at /order

'WSGIRequest' object has no attribute 'is_ajax'

error occurred while adding ajax to django project whole project stuck.

I am creating a django project and I tried with a guide. I have my code working in Development, but once I ajax added to code code get errors on ajax requests. In development, using this for submission of quizzes works perfectly well, but in development, it doesn’t. I tried using pk for the submission and it returns errors and is unable to create an accurate result instance. Below are below order.html cart.js and views.

while doing my restaurant Django project is added ajax for passing message to server . but server shows error and no output shown.

Messege shown

 if request.is_ajax(): error 
cart.js

function order(){
    var test='Ajax test';
    var ur='food/order';
    var orderData={};
    orderData['test']=test;
    $.ajax({
    url:ur,
    type:'POST',
    data:orderData,
    success:function(data){
    console.log("Data sent")}
})
}

views.py

@csrf_exempt

def order(request):
    if request.is_ajax():
        test=request.POST.get['test']
        print(test)
    ctx= {'active_link':'order'}
    return render(request,'food/order.html',ctx)

cart.js


function order(){
    var test='Ajax test';
    var ur='food/order';
    var orderData={};
    orderData['test']=test;
    $.ajax({
    url:ur,
    type:'POST',
    data:orderData,
    success:function(data){
    console.log("Data sent")}
})
}

orders.html

{% extends 'food/base.html' %}
{% load static %}
{% block title %}Order Food here {% endblock %}
{% block content %}

<div class="container-fluid m-4">
    <div class="row">
    <div class="col-md-6 text-center">
        <h3>Order</h3>
        <div class="row">
            <div class="col-md-6" id="name">
                <h5>Name</h5>
            </div>
            <div class="col-md-1" id="size">
                <h5>Size</h5>
            </div>
            <div class="col-md-2" id="price">
                <h5>Price</h5>
            </div>
        </div>
        <h5 id="total">Total :</h5>
    </div>
        <div class="col-md-1" id="rm">

        </div>
    <div class="col-md-5 mt-4">
        <h5>Messages</h5>
        <textarea name="message" id="message" cols="40" rows="5"></textarea>
        <div class="ml-auto m-4">
        <button type="submit" class="btn-success" onclick="order()">submit</button>
            </div>
    </div>
    </div>
</div>

<script src="{% static 'food/js/cart.js' %}"></script>

{% endblock %}

2

Answers


  1. HttpRequest.is_ajax() was deprecated since 3.1 version. You can read about it here – https://docs.djangoproject.com/en/4.0/releases/3.1/#id2.

    Quotation from the docs:

    request.is_ajax() can be reproduced exactly as
    request.headers.get(‘x-requested-with’) == ‘XMLHttpRequest’

    Login or Signup to reply.
  2. The error you’re encountering, "AttributeError: ‘WSGIRequest’ object has no attribute ‘is_ajax’," indicates that the request object in your Django view doesn’t have an is_ajax attribute. This is because starting from Django 3.0, the is_ajax method has been deprecated.

    To check if a request is an AJAX request in newer versions of Django, you should use the request.headers.get(‘x-requested-with’) method. Here’s how you can modify your code to fix this issue:

    Update your cart.js file to include the CSRF token in your AJAX request headers. Django requires this to prevent Cross-Site Request Forgery (CSRF) attacks.

    function order() {
        var test = 'Ajax test';
        var url = 'food/order';
        var orderData = {
            'test': test,
            csrfmiddlewaretoken: '{{ csrf_token }}', // Add this line to include CSRF token
        };
        
        $.ajax({
            url: url,
            type: 'POST',
            data: orderData,
            success: function (data) {
                console.log("Data sent")
            }
        });
    }
    

    Update your views.py file to use the request.

    headers.get('x-requested-with') method to check if it's an AJAX request:
    
    from django.http import JsonResponse
    
    @csrf_exempt
    def order(request):
        if request.headers.get('x-requested-with') == 'XMLHttpRequest':
            test = request.POST.get('test')
            print(test)
            # You can return a JSON response if needed
            return JsonResponse({'message': 'Success'})
        else:
            ctx = {'active_link': 'order'}
            return render(request, 'food/order.html', ctx)
    

    In this updated code, we check the x-requested-with header to determine if the request is an AJAX request. If it is, we process the AJAX request, and you can return a JSON response if needed. If it’s not an AJAX request, we continue to render the HTML page as before.By making these changes, you should be able to resolve the "AttributeError" and handle AJAX requests correctly in your Django project.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search