Reputation: 131
Say I am creating a Todo app in Django, traditionally I would include a path to my app in the base_project urls.py file. However, today I came across a tutorial where they used a router for this same purpose I've already stated. Why would I want to use a Router instead of including the path in my urls.py file? For reference, here is a snip from the tutorial found at https://www.digitalocean.com/community/tutorials/build-a-to-do-application-using-django-and-react
# backend/urls.py
from django.contrib import admin
from django.urls import path, include # add this
from rest_framework import routers # add this
from todo import views # add this
router = routers.DefaultRouter() # add this
router.register(r'todos', views.TodoView, 'todo') # add this
urlpatterns = [
path('admin/', admin.site.urls), path('api/', include(router.urls)) # add this
]
Here backend is the main django project name.
Upvotes: 4
Views: 3051
Reputation: 39
url_patterns is a list of definitions of individual URL routes. Each route is typically associated with a view function or a class-based view. Instead, Routers automatically handle URL routing for view sets, reducing boilerplate and making it easier to manage URLs, especially when working with RESTful patterns.
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import MyViewSet
router = DefaultRouter()
router.register(r'my-view', MyViewSet)
urlpatterns = [
path('', include(router.urls)),
]
For example, the DefaultRouter class registers the MyViewSet and handles the creation of standard RESTful routes for it (list, create, retrieve, update, partial_update, destroy). You don’t need to define each URL pattern manually.
Upvotes: 1
Reputation: 11
Both works the same. You can add url in the urlpatterns. I had the same situation as yours where in a tutorial they were using routing instead of url patteren but i studied and both works the same.
Upvotes: 1