What is a view?
A view can be used for a variety of tasks. A typical view can either be to just render a simple template, you can get information from the database and render it in a template, and similar.
Essentially what happens is that Django loops through the urls.py file and try to find a path that matches the url your visiting. When Django finds a path, it will be connected to a view. And this view will get information, do things to the information or similar, and then render a template.
Function based views vs Class based views
There are two main different ways to create views with Django. Function based views and Class based views. For beginners, it's usually easier to understand Function based views at the beginning, so this is what I will stick to.
Don't worry, I will show you later in this series how to use class based views as well :-)
The front page view
Let me show you an example, and then explain what's going on (task/views.py):
from django.shortcuts import render
def frontpage(request):
return render(request, 'task/frontpage.html')
And there it is :-)
At line 1, we import a function from Django called "render". This is used to render a template and send information to it. Then at line 3, we define a view called frontpage. This is just a typical Python function. We pass in a parameter called "request", don't worry where it comes from. The request parameter contains information about the request like browser, ip-address, if it's post or get and much more. We will use it later in this series. Then at line 4, we use the render function where we first pass in the request parameter (this makes it available for use in the template). After that, we just specify where the template is located.
from django.shortcuts import render
def frontpage(request):
title = 'This is a variable'
return render(request, 'task/frontpage.html', {'title': title})
It's not so much more complicated, but I wanted to show how to send data to the template. First I define a variable called "title", this can be called whatever you want.
And then, on the render line, we have added a little dictionary at the end where we pass in the title.
Summary
So now that we have a basic view to use, we will procede to the template tomorrow :-)
Table of contents
- 1. Introduction
- 2. Installation and setup
- 3. How things work
- 4. The first Django app
- 5. Your first view
- 6. Your first template
- 7. Testing our site
- 8. Extending templates
- 9. Your first model
- 10. The admin interface
- 11. Showing contents from the model
- 12. Another app (category)
- 13. Connecting two models
- 14. Show list of categories
- 15. Category detail page