I need to send back response with product details, so I use HttpResponseRedirect and reverse. It requires the app_name:name, so I tried something like below, but I get error:
django.urls.exceptions.NoReverseMatch: Reverse for 'product' not found. 'ProductViewSet' is not a valid view function or pattern name.
This is my view:
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def bump(request, pk):
product = get_object_or_404(Product, id=pk)
product.bumps.add(request.user)
return HttpResponseRedirect(reverse('products:product', args=[pk]))
This is my urls:
app_name = 'products'
router = DefaultRouter()
router.register(r'', ProductViewSet)
urlpatterns = [
path('', include(router.urls), name='product'),
]
What is wrong in this code? I use the correct app_name and name.
CodePudding user response:
What is wrong in this code? I use the correct
app_name
andname
.
The path you use does not link to a view: it is a path that contains a lot of subpaths, all generated by the DefaultRouter
.
You are using a router, this means that it will create different paths that will each have a specific name. These are documented in the documentation for the DefaultRouter
[drf-doc].
You thus can visit this with:
from django.shortcuts import redirect
@api_view(['POST'])
@permission_classes([IsAuthenticated])
def bump(request, pk):
product = get_object_or_404(Product, pk=pk)
product.bumps.add(request.user)
return redirect('products:product-detail', pk)