简体   繁体   中英

Django class based views get post data and send response

Working on an Api I wanted to give class based views in Django a go.

This is what I got so far:

urls.py

from django.conf.urls import url

from .api import Api

urlpatterns = [
    url(r'^', Api.as_view())
]

api.py

from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View    

class Api(View):    
    @method_decorator(csrf_exempt)
    def dispatch(self, request, *args, **kwargs):
        super(Api, self).dispatch(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        return HttpResponse("result")

    def get(self, request):
        return HttpResponse("result")

When calling this code from Postman I keep getting 2 issues:

Post data

In postman I have set a value in the Post headers but when I use the debugger to check the POST data it just isn't there.

Return HttpResponse

I keep getting the error The view api.api.Api didn't return an HttpResponse object. It returned None instead. The view api.api.Api didn't return an HttpResponse object. It returned None instead.

When I change the post method to a get method and send a get request with Postman I get the same result.

You need to do:

return super(Api, self).dispatch(request, *args, **kwargs)

You're not returning anything, and a function returns None by default.

Also, you probably want your url as r'^$'

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