Calling api from django view error. forbidden (csrf token is missing or incorrect)

642 views
Skip to first unread message

chern...@gmail.com

unread,
Jan 22, 2018, 3:03:18 AM1/22/18
to Django users

I seen alot of other solution, tried it but problem still persist.

When i do a requests.get, it works fine but when i'm doing requests.post. I got this forbidden (csrf token is missing or incorrect) error.


Here is my code

models.py

class TestPost(models.Model):
    # reminderId = models.AutoField()
    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):
    # valid_time_formats = ['%H:%M', '%I:%M%p', '%I:%M %p']
    # time = serializers.TimeField(format='%I:%M %p', input_formats=valid_time_formats, allow_null=True)
    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


I did a POST method on the url of the function but error


Forbidden (CSRF token missing or incorrect.): /test/ [22/Jan/2018 16:59:09] "POST /test/ HTTP/1.1" 403 2502


Also, how do i make the HttpResponse to display the json data from my get and post method ?

Andréas Kühne

unread,
Jan 22, 2018, 4:32:32 AM1/22/18
to django...@googlegroups.com
Hi,

You seem to be doing a very complicated setup. You are creating both the api viewset and another view. First of all - why?

Secondly, I am not sure that the csrf token will work when chaining your posts like that. 

So my main issue would be, can't you just post directly to the /api/test/ viewset?

To answer you second question, if you just use the viewset directly it will automatically display the JSON data. That is a core function in the django restframework.

Regards,

Andréas

--
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...@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/2b343676-12d3-47e7-9c2d-592580256e1a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

chern...@gmail.com

unread,
Jan 22, 2018, 5:06:35 AM1/22/18
to Django users
The reason why im using this is because i am using integrating 2 different project. The api call is suppose to call the api from another app. Further more i also need to save some of the details the was get from both post and get method

Yungjae Kim

unread,
Jan 22, 2018, 8:22:05 AM1/22/18
to Django users
You will have to either get CSRF token and send it or ignore it completely. csrf_exempt from django.views.decorators.csrf will be helpful. For HttpResponse to returning a json, pass in a stringfied dict.

chern...@gmail.com

unread,
Jan 23, 2018, 3:02:52 AM1/23/18
to Django users
Pass string dict ? 
I tried This and also return return Response({'Message': 'You have successfully register'}, status=status.HTTP_201_CREATED})
But both cannot work.
@csrf_exempt
def my_django_view(request):
if request.method == 'POST':
        r = requests.post('http://127.0.0.1:8000/api/test/', data=request.POST)
else:
r = requests.get('http://127.0.0.1:8000/api/test/', data=request.GET)
if r.status_code == 200:
return HttpResponse(request.GET)

return HttpResponse('Could not save data')

Yungjae Kim

unread,
Jan 23, 2018, 8:09:04 AM1/23/18
to Django users
You're still passing it as a dict. You could try:
return Response(json.dumps({'Message': 'You have successfully register'}), status=status.HTTP_201_CREATED})
Reply all
Reply to author
Forward
0 new messages