我想在django中创建一个5星星系统,但它一直得到这个错误:

vx6bjr1n  于 2023-02-14  发布在  Go
关注(0)|答案(2)|浏览(104)

我检查了django文档,但是我的问题没有解决[08/Feb/2023 15:57:18]"POST/courses/2/learning-django HTTP/1. 1" 403 2506错误:禁止(缺少CSRF标记。):/课程/2/学习- Django
这是我的模特

class Review(models.Model):
    course = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='reviews')
    first_name = models.CharField(max_length=50)
    last_name = models.CharField(max_length=50)
    rating = models.IntegerField(null=True, validators=[MinValueValidator(1), MaxValueValidator(5)])
    comment = models.TextField()
    created = models.DateField(auto_now_add=True)
    active = models.BooleanField(default=False)
    
    def __str__(self):
        return f'{self.first_name} {self.last_name}

我的看法:

def productDetailView(request, id, slug):
    product = get_object_or_404(Product, id=id, slug=slug, available=True)
    new_comment = None
    
    if request.method == 'POST':
        form = ReviewForm(request.POST)
        if form.is_valid():
            new_comment = form.save(commit=False)
            new_comment.course = product
            new_comment.rating = request.POST['rating']
            new_comment.save()
    else:
        form = ReviewForm()
    
    return render(request, 'shop/product_detail.html', {'product': product, 'form': form})

js函数:

$(document).ready(function(){
        $('.rate .rate-item').on('click', function(){
            var value = $(this).data('value');
            $.ajax({
                url: '{{ product.get_absolute_url }}',
                type: 'POST',
                data: {'rating': value},
                success: function(response){
                    alert('Rating saved successfully!');
                }
            });
        });
    });

我的模板

<form method="post">                                            
<div class="row">
<div class="col-md-6">
<div class="form-singel">
{{ form.first_name|attr:" placeholder:Fast name" }}
</div>
</div>
<div class="col-md-6">
<div class="form-singel">
{{ form.first_name|attr:" placeholder:Last Name"}}
</div>
</div>
<div class="col-lg-12">
<div class="form-singel">
<div class="rate-wrapper">
<div class="rate-label">Your Rating:</div>
<div class="rate">
<div data-value="1" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div>
<div data-value="2" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div>
<div data-value="3" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div>
<div data-value="4" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div>
<div data-value="5" class="rate-item"><i class="fa fa-star" aria-hidden="true"></i></div>
</div>
</div>
</div>
</div>
<div class="col-lg-12">
<div class="form-singel">
{{ form.first_name|attr:" placeholder:Comment" }}                                                                                               
</div>
</div>
{% csrf_token %} 
<div class="col-lg-12">
<div class="form-singel">
<button type="submit" class="main-btn">Post Comment</button>
</div>
</div>
</div> <!-- row -->                                 
</form>

我在我的表单中使用了csrf_token,但似乎不起作用,我在stackoverflow中搜索,没有人出现相同的错误
我该怎么修理它

mwg9r5ms

mwg9r5ms1#

如果你想进行AJAX请求,你需要添加CSRF令牌到数据体。

$.ajax({
    url: '{{ product.get_absolute_url }}',
    type: 'POST',
    data: {'rating': value, csrfmiddlewaretoken: '{{ csrf_token }}'},
    success: function(response){
        alert('Rating saved successfully!');
    }
});

原答复:https://stackoverflow.com/a/6170377/5711733

ippsafx7

ippsafx72#

基本上,您错过的是表单数据中的csrftoken
您有两种可能性:
使用@csrf_exempt定义视图:

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def productDetailView(request, id, slug):
    product = get_object_or_404(Product, id=id, slug=slug, available=True)
    new_comment = None

或者从cookie中加载变量并将其传递到头文件中(我使用的是js-cookie库,但您可以在堆栈溢出上找到满足您需要的单个函数)-例如:

$.ajax({
    url: url,
    type: 'POST',
    headers: {
        'X-CSRFTOKEN': Cookies.get('csrftoken'),
    },
    success: (data) => {
        location.reload();
    }
})

据我所知,第一个解决方案应该更安全。

相关问题