3

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.

1 Answer 1

6

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much. It is a great advice how to use basename

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.