Search code examples
javascriptpythondjangoxmlhttprequest

How can I go from my javascript to views.py of another app from present app


My javascript:

xhttp.open('POST', 'avgsize/avgpython' ,true);
    xhttp.setRequestHeader("content-type","application/json");
    xhttp.send(JSON.stringify(dates));

    xhttp.onreadystatechange=function(){
        if(this.readyState==4 && this.status==200){
            alert(this.responseText);               
            
        }
    }

My present Home app(all urls am visiting are working from this app ) urls.py:

urlpatterns = [
path('' , views.HomeBase , name="HomeBase"),
path('Home' , views.Home , name="Home"),
path('astroids' , include('Astroids.urls')),
path('nearest' , include('Nearest.urls')),
path('fastest' , include('Fastest.urls')),
path('avgsize/' , include('Avgsize.urls')),

]

My Avgsize app urls(i want to come here from Home app):

path('avgpython' , views.avgpython , name="averagesizePython"),

what changes should i make in the code so that i can go from javascript to Avgsize app and link avgpython and get access to views.avgpython. Please Help...!!


Solution

  • going on to the questions line wise

    1.) In the async request in Javascript u need to send the CSRF token with the request , incase you did not send the CSRF token with it Django server will Throw an Error stating that the request is from a different domain , to avoid all these complexity i would recommend to use csrf_exempt decorator.

    2.)In your Home urls nothing much is needed to be changed , but to keep things simple I would recommend to use the following method which reduces 1 step of forwarding the request (Considering Small Project, If in case ur project is Big u should not follow this)

    from Avgsize import views
    urlpatterns = [
    path('avgsize/avgpython' , include('views.avgpython'))
    ]
    

    3.)And in your views as I told in first point that u need to add csrf exempt in that view , this is how u need to do that.

    from django.views.decorators.csrf import csrf_exempt
    from django.http import HttpResponse
    
    @csrf_exempt
    def avgpython(request):
        return HttpResponse("You came to AvgPython Function")
    

    As far as I know I gave you the information what you wanted to get , if incase you are facing any issues in the present solution u can comment in the solution or u can even mail me at [email protected]