Django CSRF令牌未设置

时间:2020-04-09 11:57:34

标签: django vue.js web

所以我正在使用VueJS和Django。 Axios发出获取请求。当我尝试检索CSRF令牌并将其记录时,它显示为空。

这是我的序列化器:

class VehicleSerializer(serializers.ModelSerializer):

    seller = serializers.SerializerMethodField()       

    class Meta:
        model = Vehicle
        fields = ('vehicle_id', 'color', 'model', 'year', 'category', 'manufacturer', 'seller')

    def get_seller(self, instance):
        return instance.seller.customer.username

我的视图集:

class VehicleListCreateAPIView(ListCreateAPIView):
    serializer_class  = VehicleSerializer
    permission_classes = [IsAuthenticated]
    queryset = Vehicle.objects.all()

    def perform_create(self, serializer):
        request_user  = self.request.user
        try:
            seller = Seller.objects.get(customer = request_user)
        except Seller.DoesNotExist:
            seller = Seller.objects.create(customer = request_user)
            serializer.save(seller = seller)

我的网址模式:

path('vehicles/', VehicleListCreateAPIView.as_view()),

django文档中用于检索令牌的代码:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

export { csrftoken };

0 个答案:

没有答案