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 take the web request from urls.py and give the web response to templates. It may go to the data access layer in models.py 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 urls.py 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 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 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', {})
        
    or,
    
    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.