0

;0mage to process it on server and get a response without refreshing the page. I look up for some tutorials how to use AJAX and jQuery to do this but I don't have much knowledge at this matter. I'm completly stuck and have no idea what shall I do next. So far my code looks like this:

models.py

class Snip(models.Model):
    #some fields
    snip = models.FileField(upload_to="snips/")
    latex = models.TextField(default = '')

forms.py

from .models import Snip
from django import forms


class SnipForm(forms.ModelForm):
    class Meta:
        model = Snip
        fields = ['snip']

HTML:

<form id="snipForm" method="POST" enctype="multipart/form-data">
<input type="hidden" name="csrfmiddlewaretoken" value="...">
<div class="row align-items-center">
<div class="col-12">
<label for="id_snip">Snip:</label>
<input type="file" name="snip" required="" id="id_snip" class="btn-success p-2 rounded">
<input type="submit" name="upload" id="upload" class="btn btn-secondary">
</div>
</div>
</form>

JavaScript/AJAX

var upload_btn = document.getElementById("upload")

  upload_btn.addEventListener('click', function () {

  var form_data = new FormData();

  var ins = document.getElementById('id_snip').files.length; //

  if(ins == 0) return console.log("No snip!!!")
    form_data.append("file[]", snip.files[0]);
    csrf_token = $('input[name="csrfmiddlewaretoken"]').val();
    form_data.append("csrfmiddlewaretoken", csrf_token);
    headers = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'};
    console.log(form_data);
    console.log(headers);

    $.ajaxSetup({
  beforeSend: function(xhr) {
      xhr.setRequestHeader('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
  }
});

    $.ajax({
      type: 'POST',
      url: 'https://localhost:8000/docs/', // point to server-side URL
      dataType: "json",
      ContentType: "application/json",
      cache: false,
      processData: false,
      headers: headers,
      data: form_data,

      success: function (response) { // display success response
        console.log("SUCCESSSSSSSSS")
      },
      error: function (response) {
        console.log("NOPEEEEEE")
      }
  });
});

views.py

from django.shortcuts import render
from django.contrib.auth.models import User
from .models import Snip
from .forms import SnipForm
from django.http import JsonResponse
from django.core import serializers

def generate(request):
    is_ajax = request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
    if is_ajax and request.method == "POST":
        file = request.FILES['snip']
        processed_image = "Some text from OCR"
        return JsonResponse({'text':'Yay, I got text from OCR'})

    if request.method == 'GET':
        Users = User.objects.all()
        form = SnipForm()
        user_list = []
        for user in Users:
            if user.get_full_name():
                user_list.append(user.get_full_name())
        return render(request, "new.html", {'Users': user_list,     'form': form})

To sum up: The image is loaded to id_snip input tag. After clicking on id="upload" button it should be sent to django server and then to outer OCR API to receive some text back. Then it's supposed to be displayed on the front end without refreshing the page. However after clicking submit I get error:

The view docs.views.generate didn't return an HttpResponse object. It returned None instead.

My first thought was to check the is_ajax value. It occured to be false. So my question is:

  1. How can I check if the request "is AJAX"? I know in previous versions of django it was is_ajax() method but since some like 3.1 version is not recommended
  2. Is there any simple way to do it? My goal is to put received response (text) somewhere else on the page.

@UPDATE:

So I changed a bit of JavaScript/AJAX code above due to this post

I added

$.ajaxSetup({
beforeSend: function(xhr) {
  xhr.setRequestHeader('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
}
});

However on Django error page I can't see any META info such as HTTP_X_REQUESTED_WITH.

What more it seems that no data is appended to the form_data:

Output of:

console.log(form_data)
console.log(headers)

is:

FormData {}
{HTTP_X_REQUESTED_WITH: 'XMLHttpRequest'}

For now I get exactly the same error message, which is The view docs.views.generate didn't return an HttpResponse object. It returned None instead.

What might be wrong with this code? It seems fine for me

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
Wincij
  • 121
  • 10
  • What version of jquery are you using? Did you inspect request.META to see the headers there? Additionally, you can force sending the header. See https://stackoverflow.com/questions/14010851/set-request-header-jquery-ajax – Ladmerc Jul 16 '22 at 23:55
  • I'm afraid I'm not sure what to look for. The jQuery version is I guess 3.5.1: `` . What kind of header should be present? – Wincij Jul 17 '22 at 10:22
  • I mean check the contents of request.META to confirm if jquery sets the header. If it doesn't, the link I pasted above shows how to set the header yourself – Ladmerc Jul 17 '22 at 11:34

0 Answers0