Challenge - 5 Problems
ViewSets and Routers Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate2:00remaining
What is the output of this ViewSet router URL pattern?
Given the following Django REST Framework router and ViewSet, what URL pattern will be registered for the 'list' action?
Django
from rest_framework import routers, viewsets from django.urls import path, include class BookViewSet(viewsets.ViewSet): def list(self, request): pass router = routers.DefaultRouter() router.register(r'books', BookViewSet, basename='book') urlpatterns = [ path('', include(router.urls)), ]
Attempts:
2 left
💡 Hint
Remember how DefaultRouter registers routes for ViewSets using the basename and prefix.
✗ Incorrect
The DefaultRouter registers the 'list' action at the prefix path, so 'books/' is the correct URL for the list action.
❓ state_output
intermediate1:30remaining
What is the HTTP method for the 'create' action in a ViewSet?
In Django REST Framework, which HTTP method triggers the 'create' action in a ViewSet when using a router?
Attempts:
2 left
💡 Hint
Think about which HTTP method is used to add new data.
✗ Incorrect
The 'create' action corresponds to the POST HTTP method to add new resources.
📝 Syntax
advanced2:30remaining
Which option correctly registers a ViewSet with a router for nested routes?
You want to register a nested route for comments under posts using routers in Django REST Framework. Which code snippet correctly does this?
Attempts:
2 left
💡 Hint
Nested routes require a special nested router, not just string patterns.
✗ Incorrect
Option A uses NestedDefaultRouter to properly create nested routes with lookup fields.
🔧 Debug
advanced2:00remaining
Why does this ViewSet raise a 405 Method Not Allowed error?
Consider this ViewSet:
class ArticleViewSet(viewsets.ViewSet):
def retrieve(self, request, pk=None):
return Response({'id': pk})
router.register(r'articles', ArticleViewSet)
Why does a GET request to /articles/ return 405 Method Not Allowed?
Attempts:
2 left
💡 Hint
Check which actions correspond to which URLs and HTTP methods.
✗ Incorrect
GET on /articles/ calls the 'list' action, which is not defined, so 405 is returned.
🧠 Conceptual
expert3:00remaining
What is the main advantage of using routers with ViewSets in Django REST Framework?
Why do developers prefer using routers with ViewSets instead of manually defining URL patterns for each view?
Attempts:
2 left
💡 Hint
Think about how routers help with URL management and code simplicity.
✗ Incorrect
Routers simplify URL routing by automatically creating RESTful routes for ViewSets, reducing manual URL definitions.