详细信息:" CSRF失败:CSRF令牌丢失或不正确。"

时间:2016-08-24 15:34:12

标签: javascript django reactjs django-rest-framework axios

我使用过window.CSRF_TOKEN =" {{csrf_token}}"在restaurant_detail.html中的内部脚本标记,其中呈现了我发布评论的反应页面。但是我收到了一个错误。在我的onSubmit函数中,我已经安慰检查是否传递了csrf令牌,是的。是的。

我发布评论的axios代码是

class ReviewCreateAPIView(CreateAPIView):
    queryset = Review.objects.all()
    # permisssion_classes = [IsAuthenticated]

    def get_serializer_class(self):
        model_type = self.request.GET.get('type')
        slug = self.request.GET.get('slug')
        parent_id = self.request.GET.get('parent_id')
        return create_review_serializer(model_type=model_type, slug=slug, parent_id=parent_id, reviewer=self.request.user)

API / Views.py

def create_review_serializer(model_type='restaurant',slug=None, parent_id=None, reviewer=None):
    class ReviewCreateSerializer(ModelSerializer):
        class Meta:
            model = Review 
            fields = ('id','review','created',)

        def __init__(self, *args, **kwargs):
            self.model_type = model_type
            self.slug = slug 
            self.parent_obj = None 
            if parent_id:
                parent_qs = Review.objects.filter(id=parent_id)
                if parent_qs.exists() and parent_qs.count() == 1:
                    self.parent_obj = parent_qs.first()
            return super(ReviewCreateSerializer, self).__init__(*args, **kwargs)

        def validate(self, data):
            model_type = self.model_type
            model_qs = ContentType.objects.filter(model=model_type)
            if not model_qs.exists() or model_qs.count() != 1:
                raise ValidationError('This is not a valid content type')
            SomeModel = model_qs.first().model_class()
            obj_qs = SomeModel.objects.filter(slug=self.slug) # Restaurant.objects.filter(slug=self.slug)
            if not obj_qs.exists() or obj_qs.count() != 1:
                raise ValidationError('This is not a slug for this content type')
            return data 

        def create(self, validated_data):
            review = validated_data.get('review')
            print('review',review)
            if reviewer:
                main_reviewer = reviewer
            else:
                main_reviewer = User.objects.all().first()
            model_type = self.model_type
            slug = self.slug 
            parent_obj = self.parent_obj
            review = Review.objects.create_for_model_type(model_type, slug, review, main_reviewer, parent_obj=parent_obj)
            return review

    return ReviewCreateSerializer

serializers.py

url(r'^create/$', ReviewCreateAPIView.as_view(), name="reviewcreateapiview"),

urls.py

<div id="app"></div>
<script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script>

restaurant_detail.html

List<byte>

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

你做了一个简单的错误。有一个错字。请替换

  

'X-CSRF令牌'

  

'X-CSRFToken'

如果你有正确的代码,那么它应该发布你的数据。

答案 1 :(得分:0)

我不熟悉axios,但是我使用JQuery的打击代码解决了类似的问题:

  $.ajaxSetup({
    data : {
        csrfmiddlewaretoken : '{{ csrf_token }}'
    },
});

答案 2 :(得分:0)

你必须使用cookie值在ajax调用中设置标题。

.container {
    min-height: 100%;
    text-align: center;
    word-wrap: break-word;/*add this property*/
    background: green;
}