Home > Net >  error Object of type ImageFieldFile is not JSON serializable in django
error Object of type ImageFieldFile is not JSON serializable in django

Time:02-06

I'm trying to learn ajax in Django but when I ran this simple test I got this error and I can't find the reason, my Django version is 4.0

TypeError at /Customer/ Object of type ImageFieldFile is not JSON serializable Request Method: POST Request URL: http://127.0.0.1:8000/Customer/ Django Version: 4.0.1 Exception Type: TypeError

This is my js file code:

$(document).ready(function() {
$("#button_create_customer").click(function() {

    var serializData = $("#create_customer").serialize();
    $.ajax({
        url: $("create_customer").data('url'),
        data: serializData,
        dateType: 'json',
        type: 'post',
        success: function(response) {
            $("#Customer_List_View").append('<tr role="row"  >\n'  
                '<td><a href="Profile/'   response.list.id   '/">'   response.list.Fullname   '</a></td>\n'  
                '<td>'   response.list.Phone   '</td>\n'  
                '<td>'   response.list.Address   '</td>\n'  
                '</tr>')
            const sText = 'ثبت مشخصات بیمار : "  '   response.list.Fullname   '  " با موفقیت انجام گردید'
            handelAlert('success', sText)
            setTimeout(() => {
                alertBox.innerHTML = ""
            }, 3000)
        },
        error: function(error) {
            handelAlert('danger', 'خطا در ثبت');
            setTimeout(() => {
                alertBox.innerHTML = ""
            }, 3000);
        },
    })
    $("#create_customer")[0].reset();
});

});

This is my Html file code:

<form id="create_customer" enctype="multipart/form-data" method="post" style="padding: 10px;"> {% csrf_token %}{{form|crispy}} <input type="submit" id="button_create_customer" value="ثبت" > </form>

This is my View.py file code:

class List(View):
def get(self, request):
    list_customer = CustomerModel.objects.all()
    form = CustomerForm()
    return render(request, 'customer/index.html', context={
        'list_customer': list_customer,
        'form': form,
    })

def post(self, request):
    form = CustomerForm(request.POST,request.FILES)
    if form.is_valid():
        new_customer = form.save()
        return JsonResponse({'list': model_to_dict(new_customer)}, status=200)
    else:
        return redirect('Customer_List')

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