Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse for 'api' not found. 'api' is not a valid view function or pattern name with rest-framework

I have a few api with django-rest-framework, my routing is like this below.

set /api/genres under /api

from rest_framework import routers
from django.conf.urls import url
from django.conf.urls import include

router = routers.DefaultRouter()
router.register(r'genres', GenreViewSet)

urlpatterns = [
    url(r'^api/',include(router.urls), name='api'),
    path('', views.index, name='index'),

Now I want to use this url in template, so I tried two patterns, but both shows error.

How should I make the link for api??

<a href="{% url 'api' %}">api</a>
Reverse for 'api' not found. 'api' is not a valid view function or pattern name.

<a href="{% url 'genres' %}">genre</a>
Reverse for 'genres' not found. 'genres' is not a valid view function or pattern name.
like image 636
whitebear Avatar asked Jan 17 '26 23:01

whitebear


1 Answers

Router provides argument basename which is using to reverse url.

router = routers.DefaultRouter()
router.register(r'genres', GenreViewSet, basename='genres')

urlpatterns = [
    url(r'^api/',include(router.urls)),
    path('', views.index, name='index'),

Note that DRF's viewset has multiple urls. So you need to specify which one you want to use by adding specific suffix -list or -detail. First one will give you url of viewset list() and create() actions. And second using for retrieve() and update().

So in template it would be something like this:

<a href="{% url 'genres-list' %}">api</a>
like image 185
neverwalkaloner Avatar answered Jan 20 '26 11:01

neverwalkaloner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!