我已經在restaurant_detail.html中的腳本標籤中使用了window.CSRF_TOKEN =「{{csrf_token}}」,其中我的反應頁用於發佈評論。不過,我收到了一個錯誤。在我的onSubmit函數中,我已經安慰檢查csrf標記是否通過,是的。詳細信息:「CSRF失敗:CSRF令牌丟失或不正確。」
我張貼審查愛可信代碼
onSubmit(props){
console.log('csrf',CSRF_TOKEN);
axios({
method:'POST',
url:'/api/review/create/',
headers:{
'X-CSRF-Token':CSRF_TOKEN,
//'Access-Control-Allow-Origin':'*',
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data:{
review:props.review
}
})
.then(response => {
console.log('success');
})
.catch(error => {
throw("Error: ",error);
});
}
API/Views.py
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)
serializers.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
urls.p Ÿ
restaurant_detail.html
<div id="app"></div>
<script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script>
我怎麼能解決這個問題?
哦,是的!它真的解決了這個問題。感謝你的回答。 – pythonBeginner