Your first view - 30 days of Django

Your first view - 30 days of Django

/ #Django

Now it's time to create our first view and learn a little bit more about this.

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 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/

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.


So now that we have a basic view to use, we will procede to the template tomorrow :-)

Table of contents


No comments yet...

Add comment


Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.