Sunday, January 28, 2018

Re: Django view to call api

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?


On Monday, 22 January 2018 15:34:39 UTC+5:30, chern...@gmail.com wrote:

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

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/3ed8d7eb-80a1-4f0f-b315-485a712c1eab%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment