Django URLs and Views

A request in Django first comes to and then goes to the matching function in Python functions in take the web request from and give the web response to templates. It may go to the data access layer in as per the queryset.

Django Urls and ViewsIf 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 slightly different 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 ArchitectureDjango Urls Path

Django has a file under the project by default. It also has a prep-defined path for the 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 requests 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, the 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.