Introduction

In this part 3 of a multi-piece series, we continue building a messaging system. In this piece we build a way to display forum messages with Python and Postgres. In this piece, we use the Django and Psycopg2 frameworks for render, request, and a few database-related functions. In this piece, our database function we use is to execute two different “SELECT” SQL commands to view both topics and messages in separate dynamic HTML web pages. In the next piece in this multi-piece series, we will set up posting messages.

Prerequisites

See parts 1 and 2, where we developed the underlying Postgres tables, a registration form, and the SQL and Python application needed for user registration: Use Django for Forum Registration with Python and Postgres: https://oceanmedia.net/use-django-for-a-forum-part-1-registration

 

Django forum messages lesson overview

In piece 1 we created a registration screen. In piece 2, we built a dynamic HTML login form where the user typed in email address and password to sign in to the application and give us the id_user value to use in this piece 3 to view topics and messages.

Because you learned how the render and request functions work in piece 1, we will quickly go over those functions in this piece below.

Django request input

 

Syntax of Python Request Input

VALUE_RETURNED = request.post[field_name]

Example of Django Request

t_value_received = request.post["t_value_sent"]

NOTE: t_value_sent is encapsulated in quotes for good reason.

 

Example of Python Request Input

VALUE_RETURNED = request.post["id_user"]

Example of Python Render

return render("page.html", {"t_msg" : "Some text to show on the dynamic page."})

Django HTML templates

We are going to build two pages here, one being a page to display topics and another to display message detail when a user clicks on the topic for that message.

Here’s a reminder of what tbl_posts looks like:

CREATE TABLE tbl_posts (
	id serial NOT NULL,
	id_session int4 NULL DEFAULT 0,
	id_parent int4 NULL DEFAULT 0,
	id_user int4 NULL DEFAULT 0,
	t_subject_topic varchar(255) NULL,
	t_post varchar(255) NULL,
	t_note varchar(255) NULL,
	i_order int4 NULL DEFAULT 0,
	i_upvotes int4 NULL DEFAULT 0,
	d_created date NULL DEFAULT now(),
	d_changed date NULL DEFAULT now()
);

Now for the html: Name this first file “topics.html”. NOTE: We are leaving out the basic encapsulating html tags that you know by now how to include.

<body>
<h1>{{t_text_for_h1}}</h1>
<div class='div-main-outer'>
    <div class="frm-record">
        <div class="table-column-txt">
        <a href='/replyPost?id_user={{id_user}}&id_message=0'>Post new message</a>
        </div>
    </div>
{%
# The three rowset columns for this page:
# 0: id, 1: t_subject_topic, 2: d_changed
for db_record in db_records:
    id = db_record[0]
    t_subject_topic = db_record[1]
    d_changed = db_record[2]
}
    <div class="frm-record">
        <div class="table-column-txt">
        <a href='/showMessage?id_user={{id_user}}&id_message={{id}}'>{{t_subject_topic}}</a>
        </div>
        <div class="table-column-num">
        {{d_changed}}
        </div>
    </div>
{%
endfor
%}
</div>
</body>

Now for message.html: 

<body>
<h1>{{t_text_for_h1}}</h1>
<div class='div-main-outer'>
    <div class="frm-record">
        <div class="table-column-txt">
        <a href='/showTopics?id_user={{id_user}}&id_message={{id}}'>Back</a>
        </div>
    </div>
    <div class="frm-record">
        <div class="table-column-txt">
        <a href='/replyPost?id_user={{id_user}}&id_message={{id}}'>Post reply</a>
        </div>
    </div>
    <div class="frm-record">
        <div class="table-column-txt">
        {{t_post_full}}
        </div>
    </div>
</div>
</body>

Now that we have examined the more complex pieces of the sign in portion of our overall project, let’s put it all together into a comprehensive Python application.

 

Full Source Code in Python

import Django
from django.shortcuts import render
import psycopg2
import hashlib

app = Django(__name__)
@app.route("/showTopics", methods=["POST","GET"])

# Connection credentials for Postgres
t_host = "database host address"
t_port = "5432"
t_dbname = "database name"
t_user = "database user name"
t_pw = "password"
# Using Psycopg2 to create a connection object
db_conn = psycopg2.connect(host=t_host, port=t_port, dbname=t_dbname, user=t_user, password=t_pw)
# Using Psycopg2 to create a cursor object
db_cursor = db_conn.cursor()

# Set up globals
id_user = 23 # Once you have incorporated registration from piece 1 of this series of lessons, you won't want to hard code the value for id_user.
id_message = 0

def replyPost():
    # Coming in a future article.
    # Will be used to create new posts and reply
	#   to existing messages.

def showTopics():
    s = ""
    s += "SELECT"
    s += " id"
    s += ", t_subject_topic"
    s += ", d_changed"
    s += "FROM tbl_posts"
    s += "ORDER BY"
    s += " d_changed DESC"
    try:
        db_cursor.execute(s)
        # Create list of columns for the record returned:
        db_records = db_cursor.fetchall()
    except psycopg2.Error as e:
        t_msg = "SQL error: " + e + "/n SQL: " + s
        return render("error.html", {t_msg : t_msg})
    db_cursor.close()

    return render("topics.html", {db_records:db_records, id_user:id_user, t_text_for_h1 : "Forum Message Topics"})
    id_user = request.get['id_user']
    id_message = request.get['id_message']

def showMessage():
    s = ""
    s += "SELECT"
    s += " t_post"
    s += "FROM tbl_posts"
    try:
        db_cursor.execute(s)
        # Create list of columns for the record returned:
        db_record = db_cursor.fetchone()
    except psycopg2.Error as e:
        t_msg = "SQL error: " + e + "/n SQL: " + s
        return render("error.html", {t_msg : t_msg})
    db_cursor.close()

    return render("message.html", {db_record:db_record, t_text_for_h1:"Forum Full Message Detail"})

Conclusion

In this piece 3 of a 4-piece forum-building multi-piece series, we continued building the messaging system. In this section we built a way to display forum messages with Python and Postgres. We used the Django and Psycopg2 frameworks for render, request, and other database functions. In this piece, our database function we used to execute two different “SELECT” SQL commands was execute() to view topics and message content in separate server-generated HTML pages. In the next piece in this multi-piece series, we will build a feature where the user can post messages to the forum.