Skip to content

Instantly share code, notes, and snippets.

@prodeveloper
Last active July 11, 2017 05:35
Show Gist options
  • Save prodeveloper/85418d3bc2efebcb4b0b1a3112d07df5 to your computer and use it in GitHub Desktop.
Save prodeveloper/85418d3bc2efebcb4b0b1a3112d07df5 to your computer and use it in GitHub Desktop.
Passing data to the template

##Displaying data in the template

Today, we will be looking at how to display model data on your template. While previously we could show only Student Object in this lesson we will unpack that.

Step 1

Let us start by creating the template that will show the data. We can call it listing_data.html

In the file, we will put in a simple message so that we know when the page is loaded successfully.

Once this is done we wire it up at the views.py file using the usual render method

If you now navigate to your /students endpoint, you should be able to see it.

Step 2

Displaying html is all well and good but our app would not be as useful if that is all that it could do.

We need to be able to customize it by sending data to it. Django does this by using the parameter called context

The context is a simple dictionary that contains the data to be passed from the view to the template.

Let us try passing the information from the view to the template instead of coding it directly into the view.

We now edit the template so that it can show the data

Note the use of the new tag

    {{}}

This is a builtin tag in Django. When Django comes across it. It tries to print out what is contained within it.

Running your app now will give you the same output. You can modify it to see a different result.

Of interest, is that you can pass as many variables in the context as you want.

We can then display them on the view

Step 3

Now that we are able to pass information to the template. Let us pass real data from the model to the template.

We start with querying the student with id 1 on the views.py file

We then modify the template accordingly to ensure that the new data will display as expected.

When you load on your browser, you should now be able to see real data from your database.

Step 4

Let us now make this text look a bit better by introducing bootstrap.

Our template file will now look as follows:

On your browser it will look something like this:

Assignment

For your welcome page, pass the data that is displayed from the view instead of hard coding it into the template file.

Links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment