我不能从POSTMAN进行POST调用,但可以手动 - Django

时间:2016-12-14 07:33:10

标签: python django post django-rest-framework postman

我可以从Django REST Framework内置API进行POST调用,但Here you can see that result 我无法使用POSTMAN postman result

进行此类调用

还有POSTMAN的标签内扩展,显示

  

“CSRF失败:CSRF令牌丢失或不正确。”

我也以管理员身份登录,但它在POSTMAN中无效 你能说出什么是错误的

以下是代码

serializers.py

from rest_framework import serializers
from snippets.models import Snippet
from django.contrib.auth.models import *

class SnippetSerializer(serializers.HyperlinkedModelSerializer):
            class Meta:
                model = Snippet
                fields = ('title','code',)

def create(self, validated_data):
    return Snippet.objects.create(**validated_data)


def update(self, instance, validated_data):
    instance.title = validated_data.get('title', instance.title)
    instance.code = validated_data.get('code', instance.code)
    instance.save()
    return instance

Views.py

from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser
from snippets.models import Snippet
from rest_framework import viewsets
from snippets.serializers import SnippetSerializer


# Create your views here.
class SnippetViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = Snippet.objects.all().order_by('title')
    serializer_class = SnippetSerializer

2 个答案:

答案 0 :(得分:1)

那是因为您的django视图具有CSRF保护。使用邮递员时需要发布CSRF标题。您可以使用邮递员拦截器捕获这些标头,也可以使用chrome开发人员工具捕获这些标头。完成后,请确保邮递员标题选项卡中包含以下内容

Cookie:  captured session cookie, others are not needed
X-CSRFToken: Captured token something like QRG6UOm1EsD6iGCk26ELms75ho392KZlxLZeS5aP4gFNrsdI4vRRIrklpraq
Referer: http://localhost:8080 (or your live server url)

答案 1 :(得分:0)

你可以先退出,应该没问题。 或者您可以打开新的隐身窗口,在那里您将无法登录。