Home > Blockchain >  Django REST API: How to respond to POST request?
Django REST API: How to respond to POST request?

Time:10-27

I want send POST request with axios(VueJS) and when Django server got a POST request then I want to get back that request message. I tried make functions when got an POST request in Django server and then return JsonResponse({"response": "got post request"), safe=False)

JS function

            sendMessage() {
            axios({
                method: "POST",
                url: url,
                data: this.message
            })
            .then(response => {
                this.receive = response;
            })
            .catch(response => {
                alert('Failed to POST.'   response);
            })
            }
        }

views.py

from chat.serializer import chatSerializer
from chat.models import *
from rest_framework.routers import DefaultRouter
from rest_framework import viewsets
from django.http import JsonResponse
from django.views.generic import View
# Create your views here.


class get_post(View):
    def post(self, request):
        if request.method == 'POST':
            JsonResponse({"response": 'got post request'}, safe=False)

but error says like that in django

Internal Server Error: /api/chat/
Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/django/core/handlers/exception.py", line 
47, in inner
    response = get_response(request)
  File "/usr/lib/python3/dist-packages/django/core/handlers/base.py", line 188, 
in _get_response
    self.check_response(response, callback)
  File "/usr/lib/python3/dist-packages/django/core/handlers/base.py", line 309, 
in check_response
    raise ValueError(
ValueError: The view chat.views.views.get_post didn't return an HttpResponse object. It returned None instead.
[26/Oct/2022 17:06:51] "POST /api/chat/ HTTP/1.1" 500 60946

I think POST request is working properly, but Django code is something wrong.

Therefore, my question is..

  1. How to fix and solve this error?
  2. When I call axios in JS, inside '.then' we got a response so which data is come to this variable? Should I return this data like Response() or JsonResponse() method?

CodePudding user response:

just add a return in the view ... like this:

class get_post(View):
    def post(self, request):
        if request.method == 'POST':
            return JsonResponse({"response": 'got post request'}, safe=False)

because the error complains that the post function must return anything.

for the second question ya you need to return JsonResponse because you are dealing with APIs.

  • Related