Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reverse and HttpResponseRedirect don't work with DefaultRouter

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

What is wrong in this code? I use the correct app_name and name.

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading