我创建了一个审核系统,当我要提交审核时出现错误 In my views.py:

def ajex_add_review(request,pid):
    product=Product.objects.get(pk=pid)
    user=request.user

    review=ProductReview.objects.create(
        user=user,
        product=product,
        review=request.POST['review'],#1
        rating=request.POST['rating'],#2
        )
    context={
        'user':user.username,
        'review':request.POST['review'],#1
        'rating':request.POST['rating'],#2
    }
    average_reviews=ProductReview.objects.filter(product=product).aggregate(rating=Avg("rating"))

    return JsonResponse(
      {
        'bool':True,
        'context':context,
        'average_reviews':average_reviews,
      }
    )

我认为错误来自于这里.因为如果我注释掉其中的review(#1)rating(#2)个,它就运行得很好

如果您需要我的js文件,那么 在function.js:年内

console.log("working");


$("#commentForm").submit(function(e){
    e.preventDefault();

    $.ajex({
        data: $(this).serialize(),

        method: $(this).attr("method"),

        url: $(this).attr("action"),

        dataType: "json",

        success: function(response){
            console.log("Comment Saved");
        }
    })
})

在我的product-detail.html

                  <div class="add-review">
                      <h3>Add Your Review</h3>
                      <form action="{%  url 'core:ajex_add_review' p.id  %}" method="POST" id="commentForm">
                        {% csrf_token %}
                          {{review_form.rating}}
                      </form>
                      <br>
                      <form action="{%  url 'core:ajex_add_review' p.id  %}" method="POST" id="commentForm">
                        {% csrf_token %}
                          {{review_form.review}}
                          <button type="submit" class="btn">Submit</button>
                      </form>

                      <div class="rating-bar">
                        <div class="bar">
                          <div class="fill" style="width: 80%;"></div>
                        </div>
                        <div class="bar-label"><i>{{average_rating.rating|floatformat:1}} out of 5.0</i></div>
                      </div>

                  </div>

所以请帮我解决这个问题.我的缩进是正确的. 以及最后的My error is:

System check identified 2 issues (0 silenced).
March 08, 2024 - 01:45:45
Django version 4.1.13, using settings 'ecomprj.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Internal Server Error: /ajex-add-review/3/
Traceback (most recent call last):
  File "C:\Users\Sagarmoy Sadhukhan\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\datastructures.py", line 84, in __getitem__
    list_ = super().__getitem__(key)
            ^^^^^^^^^^^^^^^^^^^^^^^^
KeyError: 'rating'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Sagarmoy Sadhukhan\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\exception.py", line 56, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Sagarmoy Sadhukhan\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Sagarmoy Sadhukhan\Desktop\django ecom web\ecomprj\core\views.py", line 114, in ajex_add_review
    rating=request.POST['rating'],
           ~~~~~~~~~~~~^^^^^^^^^^
  File "C:\Users\Sagarmoy Sadhukhan\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\utils\datastructures.py", line 86, in __getitem__
    raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'rating'
[08/Mar/2024 01:45:46] "POST /ajex-add-review/3/ HTTP/1.1" 500 75801

推荐答案

问题是您的模板中有two个表单!这就是为什么你的request.POST两次包含密钥'rating'.

One review_form包含一个评级和一个 comments .所以一张表格应该就足够了.

<div class="add-review">
    <h3>Add Your Review</h3>
    <form action="{%  url 'core:ajex_add_review' p.id  %}" method="POST" id="commentForm">
    {% csrf_token %}
        {{review_form.rating}}
<--- remove stuff here ---->
        {{review_form.review}}
        <button type="submit" class="btn">Submit</button>
    </form>

    <div class="rating-bar">
    <div class="bar">
        <div class="fill" style="width: 80%;"></div>
    </div>
    <div class="bar-label"><i>{{average_rating.rating|floatformat:1}} out of 5.0</i></div>
    </div>

</div>

作为附加信息,我建议使用下面的语法,而不是request.POST

form = ReviewForm(request.POST)
if form.is_valid():
    review=ProductReview.objects.create(
        user=user,
        product=product,
        review=form.cleaned_data['review'],#1
        rating=form.cleaned_data['rating'],#2
        )
else:
    # some error

# rest of your code

这使您可以轻松地合并表单验证逻辑.

Javascript相关问答推荐

我不知道为什么我的JavaScript没有验证我的表单

是什么原因导致此Angular 16应用程序中类型错误时属性结果不存在?

GrapeJS -如何保存和加载自定义页面

Angular中计算信号和getter的区别

如何在mongoose中链接两个模型?

PDF工具包阿拉伯字体的反转数字

Next.js服务器端组件请求,如何发送我的cookie token?

检索相加到点的子项

在VS代码上一次设置多个变量格式

为什么在函数中添加粒子的速率大于删除粒子的速率?

FileReader()不能处理Firefox和GiB文件

Socket.IO在刷新页面时执行函数两次

如果NetSuite中为空,则限制筛选

Clip-Path在网页浏览器(Mozilla、Edge、Chrome)上不能正常工作,但在预览版Visual Code Studio HTML、CSS、JS上却能很好地工作

react 路由如何使用从加载器返回的数据

React数组查找不读取变量

我如何才能让p5.js在不使用实例模式的情况下工作?

在JS/TS中构造RSA公钥

已在EventListener中更新/更改异步的React.js状态对象,但不会导致组件重新呈现

带有JS模块模式的Rails的Importmap错误:";Net::ERR_ABORTED 404(未找到)&Quot;