You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django正确配置url的name属性仍报Reverse not found错误如何解决?

问题原因

你在当前应用的urls.py中声明了app_name = 'name',也就是给当前应用的路由配置了命名空间,Django反向解析路由时需要携带命名空间前缀才能定位到对应路由,否则会提示找不到路由名称。

解决方案

修改LikeView中reverse的写法,加上命名空间前缀即可:

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def LikeView(request, pk):
    product = get_object_or_404(Product, id=pk)
    product.bumps.add(request.user)
    # 增加命名空间前缀 name:
    return HttpResponseRedirect(reverse('name:detailcreate', args=[pk]))

可选优化

如果你开发的是纯后端接口不需要页面重定向,也可以直接返回响应状态代替重定向,更符合接口设计规范:

from rest_framework.response import Response
from rest_framework import status

@api_view(['POST'])
@permission_classes([IsAuthenticated])
def LikeView(request, pk):
    product = get_object_or_404(Product, id=pk)
    product.bumps.add(request.user)
    return Response({'msg':'点赞成功'}, status=status.HTTP_200_OK)

内容的提问来源于stack exchange,提问作者some nooby questions

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 17:39:03