Reputation: 21
I am new to Django and working on a project which does not involve the use of forms in Django. I have a JS which makes an AJAX POST call to my Django web service which is my backend and I just want a response from it. However I always get none on doing so. I searched a lot but was not able to find a solution. Here is my code:
My project urls.py
:
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('home/', include('demo_app.urls')),
path('admin/', admin.site.urls),
]
My app urls.py
:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('dispatcher/', views.dispatcher, name='dispatcher'),
]
My views.py
:
from django.shortcuts import render
from django.http import HttpResponse
from demo_app.models import VesselStatus
from django.db.models import Count
from django.views.decorators.csrf import csrf_exempt
def index(request):
return HttpResponse("Hello world")
@csrf_exempt
def dispatcher(request):
if request.method == "POST":
print(request.POST.get("inputText"))
return HttpResponse(request)
I dont want to use forms hence the CSRF exempt decorator
My AJAX call:
if(individual_result.toLowerCase().includes('some text'))
{
console.log("Found");
data = {
"inputText": individual_result
}
$.ajax
({
crossDomain: true,
type: "POST",
contentType: "application/json",
url:"--address-of-local--/home/dispatcher/",
data: JSON.stringify(data),
dataType: 'json',
cache: false,
success: function(response){
console.log(response)
}
})
}
For some reason I always seem to get null. Dont know what is the issue
Upvotes: 1
Views: 961
Reputation: 21
I got it. For requests that are sent other than from a HTML form, as in like my case through an AJAX call, it HAS to be accessed using request.body
ONLY
Thanks to this answer: https://stackoverflow.com/a/30879038/12806725
Upvotes: 1