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
相关产品推荐
相关产品推荐

