Django views – time to create!

Part of this chapter is based on tutorials by Django Girls Tutorial : https://tutorial.djangogirls.org

Time to get rid of the bug we created in the last chapter! :)

A view is a place where we put the "logic" of our application.

We'll create a template in the next chapter. Views are Python functions..

Views are placed in theviews.pyfile. We will add our_views_to themyfirstgame/views.pyfile.

myfirstgame/views.py

OK, let's open up this file and see what's in there:

from django.shortcuts import render

# Create your views here.

Not too much stuff here yet.

Remember that lines starting with#are comments – this means that those lines won't be run by Python.

Let's create a _view _as the comment suggests. Add the following minimal view below it:

def index(request):
    return render(request, 'myfirstgame/index.html', {})

As you can see, we created a function (def) called index that takesrequestandreturna functionrenderthat will render (put together) our template myfirstgame/index.html.

Save the file, go tohttp://127.0.0.1:8000/and see what we've got.

Another error! Read what's going on now:

This shows that the server is running again, at least, but it still doesn't look right, does it? Don't worry, it's just an error page, nothing to be scared of! Just like the error messages in the console, these are actually pretty useful.

You can read that the TemplateDoesNotExist. Let's fix this bug and create a template in the next chapter!

Learn more about Django views by reading the official documentation:

https://docs.djangoproject.com/en/2.0/topics/http/views/

results matching ""

    No results matching ""