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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With