【问题标题】:ValueError: Field 'id' expected a number but got 'favicon.ico'ValueError:字段 'id' 需要一个数字,但得到了 'favicon.ico'
【发布时间】:2021-02-04 12:03:21
【问题描述】:

我正在构建一个 BlogApp,我正在开发一个功能,但突然我在服务器运行时看到一个错误。它显示如下↓当我在浏览器中打开某些东西时出错。

一切正常,但每次点击都会显示。

ValueError:字段 'id' 需要一个数字,但得到了 'favicon.ico'。

views.py

def detail_view(request,id):
    data = get_object_or_404(Post,id=id)
    comments = data.comments.order_by('-created_at')
    new_comment = None
    comment_form = CommentForm(data=request.POST)
    post = get_object_or_404(Post,id=id)

    if post.allow_comments == True :
        if request.method == 'POST':
            if comment_form.is_valid():
                comment_form.instance.post_by = data
                comment_form.instance.commented_by = request.user
                comment_form.instance.active = True
                new_comment = comment_form.save()
                return redirect('detail_view',id=id)

        else:
            comment_form = CommentForm()

    context = {'counts':data.likes.count,'post':post,'data':data,'comments':comments,'new_comment':new_comment,'comment_form':comment_form}
    return render(request, 'show_more.html', context )

urls.py

path('<id>',views.detail_view,name='detail_view'),
**When i check this Error in Browser, it is showing `data = get_object_or_404(Post,id=id) ` IT MEANS that the error is in this line in Views.py.**

I don't know what's wrong in this.

Any help would be appreciated.

Thank You in Advance.

【问题讨论】:

  • 尝试将id 更改为pk,因为id 是python 中的内置函数。
  • 我更改了 data = get_object_or_404(Post,pk=id) 但它一直显示错误。

标签: python django


【解决方案1】:

像这样更改您的代码:

# urls.py
path('<int:pk>',views.detail_view,name='detail_view'),

在你的views.py:

def detail_view(request,id):
    data = get_object_or_404(Post,pk=pk)
    # ......
    post = get_object_or_404(Post,pk=pk)
    #......
        return redirect('detail_view',pk=pk)

希望这能解决您的问题。

【讨论】:

  • 我只是注意到您正在对数据库进行额外的查询。因为 data 和 post 变量在其中存储了相同的值。
  • 我非常感谢您的努力,但它一直显示此错误。我还删除了其他变量
  • 它也显示The above exception (invalid literal for int() with base 10: 'favicon.ico') was the direct cause of the following exception:
  • 好的!然后请将您的模板文件添加到您的问题中。因为我认为问题出在您的模板中。
  • 我已经添加了模板
猜你喜欢
  • 1970-01-01
  • 2021-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-23
  • 2020-08-26
  • 1970-01-01
  • 2021-08-31
相关资源
最近更新 更多