Reputation: 747
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
Upvotes: 1
Views: 4898
Reputation: 16763
I am not sure about the API you're calling, but I think you might need to send data
in post request and not params
.
r = requests.post('http://127.0.0.1:8000/api/test/', data=request.POST)
Upvotes: 2