ValueError:字段“id”需要一个数字但得到“favicon.ico”

时间:2021-02-04 12:03:21

标签: python django

我正在构建一个博客应用程序,我正在开发一个功能,突然我在服务器运行时看到一个错误。当我在浏览器中打开某些内容时,它显示如下 ↓ 错误。

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

<块引用>

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.

1 个答案:

答案 0 :(得分: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)

希望这能解决您的问题。