How to Write a View:

  • Remember, a view function takes in information from a web request, prepares the data needed to generate a page, and then sends the data back to the browser, often by using a template.
  • Here’s what’s in views.py (which was created automatically when we ran the python command: python manage.py startapp) currently:

views.py

python
1from django.shortcuts import render
2
3# Create your views here.
  • The following code is how the view for the home page should be written:

views.py

views.py showing the index function that takes a request and calls render with the index.html template path

  • When a URL request matches the pattern we defined in the previous page, Django will look for a function called index() in the views.py file.
  • Django then passes the request object to this view function.
  • Note the only code in this function is to call render() function which as two arguments:
    • The original request object
    • A template it can use to build the page. That brings us to templates.