What is the difference between Django's `urls.py` and `views.py`?

Beginner

Answer

  • urls.py: Contains URL patterns that map URLs to view functions. Acts as a router determining which view should handle specific URLs.
  • views.py: Contains view functions/classes that process HTTP requests and return HTTP responses. Contains the actual business logic.

Example:

# urls.py
urlpatterns = [
    path('articles/', views.article_list, name='article_list'),
]

# views.py
def article_list(request):
    articles = Article.objects.all()
    return render(request, 'articles/list.html', {'articles': articles})