Django urls and views

A request in django first comes to urls.py and then goes to the matching function in views.py. Python functions in views.py takes the web request from urls.py and gives the web response to templates. It may go to the data access layer in models.py as per the queryset.

Django Urls and Views

If we look at the 3-tier architecture of an app. Views are like the business logic layer. It is the controller in a typical MVC (Model View Controller) design but django has a slighly differnt naming convention called MVT (Model View Template) where:
Model is the data access layer,
View is the business logic layer and
Template is the presentation layer.

Django MVT Architecture

Django Urls Path

Django has a urls.py file under the project by default. It also has a prep-defined path for admin app. However, django recommends mapping all resources via another urls.py newly created under the app. The below explains it:

mysite -- urls.py

    from django.contrib import admin  
    from django.urls import path, include

    urlpatterns = [  
        path('admin/', admin.site.urls),  
        path('myapp/', include('myapp.urls')),  
    ]  
                                

myapp -- urls.py

    from django.urls import path
    from . import views

    urlpatterns = [  
        path('', views.index),  # app homepage
    ]  
                                

Django View Function

The url mapping will redirect request from project urls to app urls and then to the respective view function. A sample view function code may look like this:

    def index(request):
        return render(request, 'index.html', {})
        
    or,
    
    from django.http import HttpResponse
    def index(request):
        return HttpResponse("Hello World") 
                                

Here, request is the url request mapping and calling the view function. render combines a given template with a given context dictionary. {} denotes the dictionary of values that can be added to the template context.