从django中调用api查看错误。禁止(csrf令牌丢失或不正确)

时间:2018-01-22 08:00:48

标签: django django-rest-framework

我见过很多其他解决方案,试过但问题仍然存在。

当我做一个requests.get时,它工作正常,但是当我在做request.post时。我得到了这个禁止(csrf令牌丢失或不正确)错误。

这是我的代码

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

我在函数的url上做了一个POST方法但错误

禁止(CSRF令牌丢失或不正确。):/ test / [22 / Jan / 2018 16:59:09]“POST / test / HTTP / 1.1”403 2502

0 个答案:

没有答案