简体   繁体   中英

Ajax post call not reaching Django view

In my django site i have an API view that is supposed to increment an integer field when called. However, the ajax call says the view is an invalid url. I have tried changing the url multiple times and changing the view.

Here's the error message from console错误信息

Here's my javascript ajax call

    function post_(amount){
        return $.ajax({
            url: '127.0.0.1:8000/increment/',
            type: "POST",
            data: {
                "amount": amount,
                "user": "{{ user.username }}",
            },
            dataType: "json",
            success: function (data) {
                console.log(data);
            },
            error: function (error) {
                console.log("Error Message: ");
                console.log(error);

            }
        });
    }

Here's the django view this ajax function is supposed to call

@api_view(['POST'])
def Increment(request):
    amount = request.data['amount']
    #username_m = request.data['user']
    #profile = Profile.objects.filter(user=username_m)
    profile = get_object_or_404(Profile, user=request.user)
    print(profile)
    profile.coins += amount
    profile.save(update_fields=['coins'])
    return Response({"message": "Got some data!", "data": request.data})

And here is my urls.py

urlpatterns = [
    path('increment/', views.Increment, name='increment'),

]

Thanks

You can simply use /increment/ as AJAX url. This will add /increment/ to your localhost domain.

For Absolute path try using

url: 'http://localhost:8000/increment/' 

or

url: 'http://127.0.0.1:8000/increment/'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM