piperck
piperck

Reputation: 75

django POST can't return character string

I try testing my server and connect with android client with django. now my code was

from django.http import HttpResponse

def first_page(request):
    if request.method == 'POST':
        return HttpResponse('you are post method😞')

android client post my server was always 500 response. and if change the method.and use the if request.method == 'GET:' It worked... I'am confused what happen ...'POST method can not use HttpResponse?

Update my question: and we use java to POST my django server.and return error as blow

at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getHeaderField(Unknown Source)
    at java.net.URLConnection.getContentType(Unknown Source)

can any help us?

Upvotes: 0

Views: 280

Answers (3)

piperck
piperck

Reputation: 75

oh !!!! I solve it . and I use django 1.77 and have so many middleware default load! #the middleware will be ok!

Upvotes: 0

Atma
Atma

Reputation: 29775

Did you include CSRF Exempt ribbon your function?

@csrf_exempt 
def my_method(request):

Upvotes: 0

Tim Saylor
Tim Saylor

Reputation: 1054

I would make your view a bit more robust to make sure you're not overlooking a silly mistake. Your view should always return an HttpResponse object, so either add a return after the if block, like this:

from django.http import HttpResponse, HttpResponseBadRequest

def first_page(request):
    if request.method == 'POST':
        return HttpResponse('you are post method😞')
    return HttpResponseBadRequest('Request type {} is not allowed'.format(request.method))

Or add django's built in request type decorator to require a post before your view code runs:

from django.http import HttpResponse
from django.views.decorators.http import require_POST

@require_POST
def first_page(request):
    return HttpResponse('you are post method😞')

Then make sure you have settings.DEBUG set to True and see what you get from your android client.

Upvotes: 2

Related Questions