0

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

2
  • "I did a POST method on the url of the function but error" <-- how do you do this? If you are using SessionAuthentication you need to pass a valid CSRF token as described in django-rest-framework.org/topics/ajax-csrf-cors/….
    – dukebody
    Jan 22, 2018 at 19:29
  • Ah, that url is from my local project. I have 2 different django project , P1 and P2. I am using P1 to call P2 api using postman. Jan 23, 2018 at 1:28

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.