Django urls and views

A request in django first comes to and then goes to the matching function in Python functions in takes the web request from and gives the web response to templates. It may go to the data access layer in 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 file under the project by default. It also has a prep-defined path for admin app. However, django recommends mapping all resources via another newly created under the app. The below explains it:

mysite --

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

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

myapp --

    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', {})
    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.