Django view to call api

27 views
Skip to first unread message

chern...@gmail.com

unread,
Jan 22, 2018, 5:04:39 AM1/22/18
to Django users

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

Akhil Lawrence

unread,
Jan 28, 2018, 12:32:11 PM1/28/18
to Django users
Looking at the log you have posted I guess you are not sending any data to the api. Look at the query dicts, the second one is empty. What is the message that you get along with the 400 response?
Reply all
Reply to author
Forward
0 new messages