Home:ALL Converter>Django view to call api

Django view to call api

Ask Time:2018-01-22T18:03:33         Author:Jin Nii Sama

Json Formatter

So i'm using django view to call api post method but its giving me 400 error

As i encounter csrf forbidden error b4, im using the @csrf_exempt for now. I tried doing post method on both the API itself and also using the view to call the api.

However when using the view to call, i got 400 error when both are using the same post value to post.

Posting using api: QueryDict: {'book': ['Second '], 'author': ['Ban'], 'date': ['2018-01-10 08:00AM']} [22/Jan/2018 18:56:09] "POST /api/test/ HTTP/1.1" 200 61

Posting using view: QueryDict: {} [22/Jan/2018 18:56:12] "POST /api/test/?book=Second+&author=Ban&date=2018-01-10+08%3A00AM HTTP/1.1" 400 36 [22/Jan/2018 18:56:12] "POST /test/ HTTP/1.1" 200 19

Here is my code

models.py

class TestPost(models.Model):
    book = models.CharField(max_length=10, blank=True, null=True)
    author = models.CharField(max_length=10, blank=True, null=True)
    date = models.DateTimeField(blank=True, null=True)

serializer.py

class TestPostSerializer(serializers.ModelSerializer):
    date = serializers.DateTimeField(format="%Y-%m-%d %I:%M %p")

    class Meta:
        model = TestPost
        fields = ('id', 'book', 'author', 'date')

views.py

from django.http import HttpResponse
import requests

def my_django_view(request):
    if request.method == 'POST':
        r = requests.post('http://127.0.0.1:8000/api/test/', params=request.POST)
    else:
        r = requests.get('http://127.0.0.1:8000/api/test/', params=request.GET)
    if r.status_code == 200:
        return HttpResponse('Yay, it worked')
    return HttpResponse('Could not save data')

class TestPostViewSet(viewsets.ModelViewSet):
    permission_classes = [AllowAny]
    queryset = TestPost.objects.all()
    serializer_class = TestPostSerializer

Author:Jin Nii Sama,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/48378910/django-view-to-call-api
yy