Django中使用reverse()反转@action定义的URL的正确名称是什么?
问题分析与解决方法
核心问题
@action装饰器是Django REST Framework中ViewSet类的专属特性,APIView并不支持这个装饰器。你把它用在APIView子类上,导致order_created端点根本没被正确注册到路由中,自然无法通过reverse找到对应名称。
解决方案
方案1:改用ViewSet(推荐)
将ShopifyWebhookAPIView改为继承ViewSet(或其子类),让@action生效:
from rest_framework.viewsets import ViewSet from rest_framework.response import Response from rest_framework.decorators import action class ShopifyWebhookViewSet(ViewSet): @action(detail=False, methods=['post'], url_path='(?P<webshop_name>.+)/order_created', name='order-created') def order_created(self, request, webshop_name=None): return Response({'message': f'Order created for {webshop_name}'})
调整ws_shopify.urls的路由配置,用DRF的路由器注册:
from django.urls import path, include from rest_framework.routers import DefaultRouter from .views import ShopifyWebhookViewSet router = DefaultRouter() router.register(r'api/shopify', ShopifyWebhookViewSet, basename='webhook') urlpatterns = [ path('', include(router.urls)), ]
此时正确的reverse写法:
reverse('shopify:webhook-order-created', kwargs={'webshop_name': 'test-shop'})
(ViewSet的action名称会自动拼接为{basename}-{action-name}格式)
方案2:继续使用APIView,手动添加URL
如果不想改用ViewSet,需在ws_shopify.urls中手动添加对应URL路径:
from django.urls import path from .views import ShopifyWebhookAPIView urlpatterns = [ path('api/shopify/', ShopifyWebhookAPIView.as_view(), name='webhook'), # 手动注册order_created的URL path('api/shopify/<str:webshop_name>/order_created/', ShopifyWebhookAPIView.as_view({'post': 'order_created'}), name='order-created'), ]
此时正确的reverse写法:
reverse('shopify:order-created', kwargs={'webshop_name': 'test-shop'})
补充说明
你之前尝试的shopify:webhook:order-created写法错误,因为webhook是单个URL的name,并非子namespace,只有通过include指定namespace时才会形成层级结构。
内容的提问来源于stack exchange,提问作者physicalattraction
相关产品推荐
相关产品推荐

