CodingNeed.

1 · Structure and rendering · 30 MIN

Django URL patterns and views

A view turns a routed request into a response.

Django matches URL patterns in order and passes captured values to the selected view. JsonResponse serializes a Python value into a JSON response; safe=False permits a top-level list for this public catalog. A method restriction makes the read-only contract explicit. Keep URL routing separate from business calculations so the latter can be tested as ordinary functions. This first lesson uses static public data; authentication and ownership become necessary when a route exposes personal records.

Register the app and URL configuration in the project.

Read the example

# courses/views.py
from django.http import JsonResponse
from django.views.decorators.http import require_GET
@require_GET
def catalog(request):
    return JsonResponse([{"id": "react", "title": "React foundations"}], safe=False)
# learning/urls.py (separate file)
from django.urls import path
from courses.views import catalog
urlpatterns = [path("courses/", catalog)]
Check the expected output
GET /courses/ returns one public course; POST to the same view is rejected with 405.

Your challenge

Add a detail route using a string slug and return a JSON 404 when the course is unknown.

Solution cost: O(r) route matching in a small ordered route set. time · O(1) fixed example payload. space

Common trap

A route parameter identifies a candidate record; it does not authorize access.

Study the project implementation
# courses/views.py
from django.http import JsonResponse
from django.views.decorators.http import require_GET
@require_GET
def catalog(request):
    return JsonResponse([{"id": "react", "title": "React foundations"}], safe=False)
# learning/urls.py (separate file)
from django.urls import path
from courses.views import catalog
urlpatterns = [path("courses/", catalog)]

Further reading: Official documentation

Next lesson: Django models and database constraints

Essential cookies keep your account signed in. Optional analytics is not configured on this site. Your choice does not affect access to lessons.

Read the Privacy Policy. You can change this choice in the footer.