Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python Flask and Jinja syntax. How to get a name to show on another page?

pc510

Coder
I am trying to make a web app using Flask, but I am having trouble with the Jinja syntax. I am following CS50. I want to take the student's name and dorm from index.html and display it on success.html. However, I am unable to do this. All that displays is

"You have successfully registered! from has registered." Whereas I want it to say "You have successfully registered! [STUDENT] from [DORM NAME] has registered."

Here is the main.py code

Code:
from flask import Flask, render_template, request
import csv

app = Flask(__name__)

students = []

@app.route('/')
def index():
    # does this go here?

    return render_template('index.html')


@app.route('/register', methods=["POST", "GET"])
def register():

    name = request.form.get("name")

    if not request.form.get("name") or not request.form.get("dorm"):
        return "Failure!"
    file = open("registered.csv", "a")
    writer = csv.writer(file)
    writer.writerow((request.form.get("name"), request.form.get("dorm")))
    file.close()

    return render_template("success.html")



@app.route('/registered')
def registered():
    file = open("registered.csv", "r")
    reader = csv.reader(file)
    students = list(reader)
    return render_template("registered.html", students=students)

@app.route("/registrants")
def registrants():
    file = open("registered.csv", "r")
    reader = csv.reader(file)
    students = list(reader)
    return render_template("registered.html", students=students)

Here is the index.html code
Code:
{% extends "layout.html" %}

{% block body %}
<h1>register</h1>
    <form action="/register" method="post">
        <input name="name" placeholder="Name" type="text" id="name">

        <select name="dorm" method="post">
            <option disabled selected value="" id="dorm" name="dorm">Dorm</option>
            <option value="apley court">apley court</option>
            <option value="candy">candy</option>
            <option value="d dorm">d dorm</option>

        </select>
        <input type="submit" value="Register"><br>
        <p>Or see who else is <a href="{{ url_for('registered') }}">REGISTERED</a></p>
    </form>
{% endblock %}

And here is the success.html code
Code:
{% extends "layout.html" %}

{% block body %}
    You have successfully registered!
    {{ name }} from {{ dorm }} has registered.
{% endblock %}

My guess is that the problem is in the success.html code, but I cannot figure out what I am doing wrong and why I cannot grab the input variables from the html inputs. Any help would be much appreciated. Thank you!
 
setup
templates
... index/form.html
... success.html

server.py

server.py
Python:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route('/')
def home():
    return render_template('index.html')
@app.route('/success/', methods=['GET', 'POST'])
def success():
    if request.method == 'POST':
        data = request.form
        return render_template('success.html', data=data)
if __name__ == '__main__':
    app.run()

index/form.html
HTML:
<style>
    div {
        margin: 2em;
    }
</style>

<form action="/success/" method="POST">
    <div>
    <input type="text" name="name" placeholder="Name" id="name">
    </div>
    <div>
    <select name="dorm" id="dorm">
        <option disabled selected value="">Dorm</option>
        <option value="apley court">apley court</option>
        <option value="candy">candy</option>
        <option value="d dorm">d dorm</option>
    </select>
    </div>
    <div>
    <input type="submit" value="Register">
    </div>
</form>

success.html

HTML:
<p>
    <h1>{{data['name']}}, you have successfully registered.</h1>
    {{data['name']}} from {{data['dorm']}} dorm
</p>
 
Code:
<h1>{{data['name']}}, you have successfully registered.</h1>
{{data['name']}} from {{data['dorm']}} dorm has registered.
This code is working great. Thanks! I was having some trouble saving the content to the CSV file, so I rewrote the code to look like this. I combined the success and register pages.

index.py:

Code:
from flask import Flask, render_template, request
import csv

app = Flask(__name__)

students = []

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/success', methods=['POST','GET'])
def success():
    if request.method == 'POST':
        data = request.form # this returns the data from the form?
        return render_template('success.html', data=data)

@app.route('/register', methods=["POST", "GET"])
def register():
    name = request.form.get("name")
    if not request.form.get("name") or not request.form.get("dorm"):
        return "Failure!"
    file = open("registered.csv", "a")
    writer = csv.writer(file)
    writer.writerow((request.form.get("name"), request.form.get("dorm")))
    file.close()
    if request.method == 'POST':
        data = request.form
        return render_template('success.html', data=data)

@app.route('/registered')
def registered():
    file = open("registered.csv", "r")
    reader = csv.reader(file)
    students = list(reader)
    return render_template("registered.html", students=students)


I had a quick follow up question. For the code

Code:
<h1>{{data['name']}}, you have successfully registered.</h1>
{{data['name']}} from {{data['dorm']}} dorm has registered.

where are the 'name' and 'dorm' within the [ ]? Is this the "id" from the HTML input section?
 
Kinda went a little further with your project. Plan on adding a database to hold the data at some point.
I'm using an html table that I done a few days back.
Sorry about all the lines of code.
directory setup
/ root
----__init__.py
----/static
--------/css
--------/js
--------/images
----/templates
--------all html files

__init__.py
Python:
from flask import Flask, render_template, request, redirect, url_for, session
import json
# File path, Must have read/and write by the server
file = '/var/www/FlaskApp/student.json'
# Open and load json file
with open(file, 'r') as jsonfile:
    students_data = json.load(jsonfile)
# Create the app
app = Flask(__name__)
# Ucomment to run standalone
# app.secret_key = '123@'
# Set the app root and redirect to home/start page
@app.route('/', methods=['GET'])
def index():
    return redirect(url_for('home'))
# Main view page
@app.route('/home')
def home():
    session['students'] = students_data
    return render_template('home.html')
# Form page
@app.route('/form')
def form():
    return render_template('form.html')
# Function for registering data and storing in a session for site wide use
@app.route('/register', methods=['POST', 'GET'])
def register():
    if request.method == 'POST':
        # Will be writing data to json file here
        session['data'] = request.form
        return redirect(url_for('success'))
# View for success page
@app.route('/success/')
def success():
    data = session.get('data')
    return render_template('success.html', data=data)
# View for students in json file
@app.route('/students')
def students():
    return render_template('students.html')
# Run the app
if __name__ == '__main__':
    app.run()

css files
form.css
CSS:
.myform {
    box-shadow: 0 0 8px black;
    border-radius: 20px;
    border-spacing: .5em;
    color: white;
    font-weight: bold;
    text-shadow: 1px 1px 2px black;
    background-image: linear-gradient(skyblue, lightsteelblue);
    padding: 8px;

}
.myform table {
    width: auto;
}
.myform th {
    background-color: transparent;
}

.myform input {
    position: relative;
    margin: auto;
    width: 100%;
}

.myform td {
    padding: 4px 12px 6px 4px;
    background-color: transparent;
    border: solid 1px rgb(50,50,50);
}

.myform h4 {
    margin: 2px 0 8px 4px;
}

.myform .btn, .myform select {
    cursor: pointer;
    margin-left: 4px;
}

student.css
CSS:
h1 {
    background-image: linear-gradient(skyblue, lightsteelblue);
    text-align: center;
    padding: .5em;
    color: white;
    text-shadow: 0 0 2px black;
    box-shadow: 0 0 5px black;
    border-radius: 10px;
}

.tab {
    padding: 1em;
    background-color: skyblue;
    width: 400px;
    margin: 1em 0 0 0;
    line-height: 2em;
    box-shadow: 0 0 8px rgb(30,30,30);
    border-radius: 8px;
}

style.css
CSS:
html,
body {
    height: 96%;
}

table {
    position: relative;
    top: 2%;
    left: 5%;
    width: 90%;
    height: 100%;
    border-spacing: 0;
}

th {
    height: 10%;
    font-size: 3em;
    background-color: lightsteelblue;
    border-radius: 20px 20px 0 0;
    color: white;
    text-shadow: 0 0 5px rgb(30, 30, 30), 0 0 6px rgb(255, 255, 255);
}

.logo {
    float: left;
    position: relative;
    left: 35%;
}

.mid {
    background-color: steelblue;
}

.midrow {
    background-image: linear-gradient(lightsteelblue, steelblue);
}

td {
    vertical-align: top;
    background-color: steelblue;
}

.left,
.right {
    width: 15%;
    height: 85%;
    background-image: linear-gradient(lightsteelblue, steelblue);
}


h3 {
    text-align: center;
    background-color: dodgerblue;
    margin: 4px;
    color: white;
    text-shadow: 1px 1px 3px rgb(10, 10, 10);
    border-radius: 10px 10px 0 0;
    text-decoration: underline;
}

ul {
    list-style-type: none;
}

ul li {
    margin: 4px 0 4px 0;
}

.mid {
    box-shadow: inset 0 0 4px 5px rgba(30, 30, 30, .5);
    border-radius: 20px;
    background-image: radial-gradient(rgb(200, 200, 200), rgb(255, 255, 255) 70%, rgb(200, 200, 200));
    padding: 2em;
}

.footer {
    background-color: steelblue;
    border-radius: 0 0 20px 20px;
    text-align: center;
    padding-top: 16px;
    color: white;
    text-shadow: 0 0 3px rgb(30, 30, 30);
    font-size: 1.25em;
}

a:any-link {
    color: blue;
}

a:hover {
    color: cyan;
    text-shadow: 0 0 3px black;
}

p {
    font-size: 1.25em;
    font-family: tahoma;
    font-style: italic;
}

#clock {
    font-size: 14px;
}

#date {
    font-size: 14px;
    padding-left: 2.5em;
}

.date-time {
    background-color: dodgerblue;
    margin: -4px 4px 4px 4px;
    padding: 4px;
    color: white;
    text-shadow: 2px 2px 2px black;
    border-radius: 0 0 10px 10px;
}

success.css
Code:
.success-table {
    height: auto;
    border-spacing: .15em;
    border-radius: 20px;
    padding: 1em;
    box-shadow: 0 0 5px black;
}

.success-table td {
    padding: 8px;
    background-color: steelblue;
    color: white;
    text-shadow: 1px 1px 2px black;
}

.success-table th {
    font-size: 1.75em;
}

.tleft {
    width: 15%;
}

.success-table .tfoot {
    height: 20px;
    background-color: lightsteelblue;
    border-radius: 0 0 20px 20px;
   
}

template files
index.html
HTML:
<!DOCTYPE html>
<html lang='us'>

<head>
    <title>My Page</title>
    <link rel="stylesheet" href="/static/css/style.css">
    <script type="text/javascript" src="/static/js/clock.js"></script>
    <script type="text/javascript" src="/static/js/date.js"></script>
</head>

<body>

    <table>
        <tr>
            <th colspan="3">
                <img class="logo" src="/static/images/ratt.svg" width="80px">
                My Page Heading
            </th>
        </tr>

        <tr class="midrow">
            <td class="left">
                <h3>Menu</h3>
                <ul>
                    <li><a href="{{url_for('home')}}">Home</li>
                    <li><a href="{{url_for('form')}}">Register</li>
                    <li><a href="{{url_for('students')}}">View Registery</li>
                </ul>
            </td>
            <td class="mid">
                {% block body %}    

                {% endblock %}
            </td>
            <td class="right">
                <h3>Current Date / Time</h3>
                <div class="date-time">
                    <span id="date"></span>
                    /
                    <span id="clock"></span>
                </div>
                <script>
                    currentTime();
                    currDate();
                </script>
               
            </td>
        </tr>

        <tr>
            <td colspan="3" class="footer">Gaming-Rat Productions &copy: 11/06/2022</td>
        </tr>
    </table>

</body>

</html>
form.html
HTML:
{% extends 'index.html' %}
{% block body %}
<link rel="stylesheet" href="/static/css/form.css">
<form action="/register" method="post">
    <table class="myform">
        <tr>
            <th colspan="2">Register</th>
        </tr>
        <tr>
            <td>First Name:</td>
            <td>
                <input type="text" name="fname" placeholder="First Name">
            </td>
        </tr>
        <tr>
            <td>Last Name</td>
            <td>
                <input type="text" name="lname" placeholder="Last Name">
            </td>
        </tr>
        <tr>
            <td>
                <h4>Dorms</h4>
                <select name="dorm">
                    <option value="apley court">Apley Court</option>
                    <option value="candy">Candy</option>
                    <option value="d dorm">D Dorm</option>
                </select>
            </td>
            <td></td>
        </tr>
        <tr>
            <td>
                <input class="btn" type="submit" value="Register">
            </td>
            <td></td>
        </tr>
    </table>
</form>

{% endblock %}

home.html
HTML:
{% extends 'index.html' %}
{% block body %}

<h1>Start Page</h1>
{% endblock %}


student.html
HTML:
{% extends 'index.html' %}
{% block body %}
<link rel="stylesheet" href="/static/css/student.css">
<h1>Student Registery</h1>
{% set data = session.get('students') %}

{%for s in data.values()%}
{%for item in s%}
<div class="tab">
<strong>Name:</strong> {{item['lname'].title()}}, {{item['fname'].title()}}
<br>
<strong>Dorm:</strong> {{item['dorm'].title()}}
</div>
{%endfor%}
{%endfor%}
{% endblock %}

success.html
HTML:
{% extends 'index.html' %}
{% block body %}
<link rel="stylesheet" href="/static/css/success.css">
<table class="success-table">
    <tr>
        <th colspan="2">Information Registered</th>
    </tr>

    <tr>
        <td class="tleft">Name:</td>
        <td>{{data['fname'].title()}} {{data['lname'].title()}}</td>
    </tr>

    <tr>
        <td class="tleft">Dorm:</td>
        <td>{{data['dorm'].title()}}</td>
    </tr>

    <tr>
        <td class="tfoot" colspan="2"></td>
    </tr>
</table>
{% endblock %}

Javascript files

clock.js
JavaScript:
function currentTime() {
    let date = new Date();
    let hh = date.getHours();
    let mm = date.getMinutes();
    let ss = date.getSeconds();
    let session = "AM";

    if (hh == 0) {
        hh = 12;
    }
    if (hh > 12) {
        hh = hh - 12;
        session = "PM";
    }

    hh = (hh < 10) ? "0" + hh : hh;
    mm = (mm < 10) ? "0" + mm : mm;
    ss = (ss < 10) ? "0" + ss : ss;

    let time = hh + ":" + mm + ":" + ss + " " + session;

    document.getElementById("clock").innerText = time;
    let t = setInterval(function () {
        currentTime()
    }, 1000);
}

date.js
JavaScript:
function currDate() {
    var date = new Date()
    var weekday = date.toLocaleString('en-us', {weekday: 'short' });
    var month = date.toLocaleString('en-us', {month: 'long'});
    var day = date.getDate();
    var year = date.getFullYear();
   
    var curdate = weekday + ' ' + month + ' ' + day + ' ' + year;
    document.getElementById('date').innerHTML = curdate;
}
 

Attachments

  • window.png
    window.png
    228.8 KB · Views: 3
Last edited:
Wow, thanks menator. This is really helpful! And this will also help others with similar issues. This is super clear, and it is nice to see how the code works on a more detailed project. Look forward to seeing the code and the app when it's all done!
 
all Files and folders
There is not much error checking in the app so, you will probably find bugs.

To view this content we will need your consent to set third party cookies.
For more detailed information, see our cookies page.
 

Attachments

Last edited:
Back
Top Bottom