Django is an MVC, or model-view-controller framework, but Django doesn’t call templates views, it calls them templates.
And it doesn’t call functions that return rendered templates controllers, it calls those functions views.
To create a view, you need two things:
- A view function
- A route
Create A View Function
Create view.py
from django.http import HttpResponse
def hello_world(request):
return HttpResponse('Hello world!')
All views have to accept a request. The convention is to call the argument request
HttpResponse
is the class that represents an HTTP response back to the client.
The way we used it is the absolute simplest way of generating a response.
Create A Route
Open urls.py
...
from . import views
urlpatterns = [
url('^admin/', include(admin.site.urls)),
url('^$', views.hello_world),
]
...
.
Current directory
views.hello_world
Passing the view function without parantheses because we don’t want to call it.