Mark As Completed Discussion

Getting Data from the Database

So far, we have seen how to send static text and a semi-dynamic one but we need to do more.

In this section, we'll get data from our database to show to the user instead. Let's head over to the home view function and make some changes;

PYTHON
1# ./crud_app/views.py
2...
3def home(request):
4    posts = CRUDPost.objects.all()
5    return render(request, "crud_app/home.html", {"posts":posts})
6...

Here, we have retrieved all posts from our database using CRUDPost.objects.all(), stored them in a variable then sent that variable to our template as a dict, then in our template, we iterate through the posts, and list our the items with a for loop tag:

SNIPPET
1{% for post in posts %}
2...
3{% endfor %}

Next, we'll add a way to navigate to the post details screen when the title is clicked. Django provides a way to call a URL from within the template, we do this using the url tag, calling the name of the URL path, and any additional arguments like so

SNIPPET
1<a  href="{% url  'get_post'  post.id %}">{{ post.post_title }}</a>

Now, to show the post details, we'll need to modify the get_post view function and create a template for it:

PYTHON
1# ./crud_app/views.py
2...
3def get_post(request, post_id):
4    post = obj = get_object_or_404(CRUDPost, id=post_id)
5    return render(request, "crud_app/post_detail.html", {"post":post})
6...

Here we have used one of Django's shortcut functions (get_object_or_404) which will try to get the post with the given id or raise a 404_NOT_FOUND error if it cannot find it.

Now for the template, create a new file in the template directory, call it post_detail.html and add the following contents:

SNIPPET
1<!-- ./crud_app/templates/crud_app/post_detail.html -->
2{% extends 'base.html' %}
3{% load static %}
4{% block title %} {{ post.title }}  {% endblock title %}
5{% block content %}
6
7<div class="col-lg-12 blog-post">
8
9  <article class="post" style="padding-top:1em; border-bottom: none;">
10    <div class="inner">
11      <header class="post-header">
12        <h1 class="post-title">{{ post.post_title }}</h1>
13        <span class="post-meta">
14          @{{post.post_author}} | {{ post.date_created | date:"M j, Y"}}
15        </span>
16        <div class="clear"></div>
17      </header>
18
19      <section class="post-content">
20        <p>{{ post.post_content }}</p>
21      </section>
22    </div>
23  </article>
24</div>
25{% endblock  %}

Now whenever we click on the title of a post on the home page, we will be brought to the details page for that post.

Getting Data from the Database