Django空路径404错误求助:常规修复方案无效
问题排查与修复方案
核心错误点1:类视图与函数视图装饰器混用
你的OrganizationListView、ShopView、shops_file都是继承APIView的类视图,但错误使用了仅适用于函数视图的@api_view装饰器,导致视图无法被Django正确识别。
修复:移除类视图上的@api_view装饰器,类视图的权限控制直接通过类属性permission_classes定义,请求逻辑通过重写get/put等方法实现。示例如下:
class OrganizationListView(APIView): permission_classes = [IsAuthenticated] # 类内定义权限 def get(self, request): try: organizations = Organization.objects.filter(is_deleted=False) serializer = OrganizationSerializer(organizations, many=True) logging.info('GET request was successful') return Response(serializer.data, status=status.HTTP_200_OK) except Exception as e: logging.error(f'An error occurred while executing the request: {e}') return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
核心错误点2:URL配置中类视图未调用.as_view()
在shop.urls.py中,你直接将类视图名传入path,但Django要求类视图必须通过.as_view()方法转换为可调用的视图函数。
修复:所有类视图的路径都需添加.as_view():
urlpatterns = [ path('api/organizations/', views.OrganizationListView.as_view(), name='organizations-list'), path('api/organizations/<int:id>/shops_file/', views.shops_file.as_view(), name='get-shops-file'), path('api/shops/<int:id>/', views.ShopView.as_view(), name='shop-view'), # 其余路径保留 ]
核心错误点3:shops_file视图类的方法名错误
shops_file继承自APIView,但你定义的方法是def shops_file(self, request, id),而APIView要求对应请求的方法名(比如GET请求需写def get),否则无法匹配请求。
修复:将方法名改为get,同时修正文件名生成逻辑和文件返回方式:
class shops_file(APIView): permission_classes = [IsAuthenticated] def get(self, request, id): # 方法名改为get try: organization = Organization.objects.get(id=id) shops_csv = organization.shop_set.all() data_shops = [{'id': shop.id, 'name': shop.name} for shop in shops_csv] df = pd.DataFrame(data_shops, columns=["id", "name"]) filename = f"shops_{organization.id}.xlsx" # 修正文件名变量 df.to_excel(filename, index=False) logging.info('The request was successful') # 用HttpResponse返回二进制文件,设置正确响应头 response = HttpResponse(open(filename, 'rb'), content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = f'attachment; filename="{filename}"' return response except Organization.DoesNotExist: logging.error(f'Organization with id={id} not found') return Response(f'Organization with id={id} not found', status=status.HTTP_404_NOT_FOUND) except Exception as e: logging.error(f'An error occurred while executing the request: {e}') return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
根路径404的补充处理
你访问的空路径(如http://localhost:8000/)没有对应视图,若需要根路径有响应,可在shop.urls.py中添加:
path('', yasg_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'),
或者自定义一个简单视图返回API说明。
完成以上修复后,重启服务器,通过/api/v1/token/获取认证令牌后,即可正常访问对应API路径。
内容的提问来源于stack exchange,提问作者Dany_Blum
相关产品推荐
相关产品推荐

