2

I am trying to display certain information on a template. Everything in the python code works perfectly but anything and everything inside the for loop is not getting displayed inside the template. I believe that I have passed everything correctly. Could someone please help me to display the tutor info in my 'display.html'? I also want to mention that whatever I am trying to display should be available for all users to see and not just me. The file will keep getting updated as more and more users register as a tutor. This should update and show everyone who has signed up to all the users. Code will be below. Thanks in advance!

main.py

    #main.py

    from flask import Flask, request, session, render_template, redirect, url_for, flash, get_flashed_messages
    from flask.globals import current_app
    from flask_login import LoginManager, login_user, login_required, logout_user, current_user, UserMixin
    from datetime import timedelta, datetime
    from werkzeug.security import generate_password_hash, check_password_hash
    import sqlite3
    from os import error, path
    from flask_sqlalchemy import SQLAlchemy
    from flask_mail import Mail, Message

    app = Flask(__name__)
    DB_NAME = "spark.db"
    app.config["SECRET_KEY"] = "1986319249872139865432"
    app.config['SQLALCHEMY_DATABASE_URI'] = f"sqlite:///{DB_NAME}"
    app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

    db = SQLAlchemy(app)
    db.init_app(app)

    def create_database(app):
        if not path.exists(DB_NAME):
            db.create_all(app=app)
            print("Created Database!")

    class Tutor(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
        tremail = db.Column(db.String(10000))
        trusername = db.Column(db.String(1200))
        subjects = db.Column(db.String(1200))
        session_length = db.Column(db.String(1200))


    class User(db.Model, UserMixin):
        id = db.Column(db.Integer, primary_key=True)
        email = db.Column(db.String(150), unique=True)
        username = db.Column(db.String(150))
        password = db.Column(db.String(150))
        tutors = db.relationship('Tutor')


    create_database(app)

    login_manager = LoginManager()
    login_manager.login_view = 'login'
    login_manager.init_app(app)
    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))


    @app.route("/")
    @login_required
    def home():
        return render_template("index.html")

    @app.route("/login", methods=["GET", 'POST'])
    def login():
        if request.method == "POST":
            email = request.form.get('email')
            password = request.form.get('password')

            user = User.query.filter_by(email=email).first()
            if user:
                if check_password_hash(user.password, password):
                    flash('Login successful!', category="success")
                    login_user(user, remember=True)
                    return redirect(url_for("home"))
                else:
                    flash('Incorrect password! Please try again.', category="error")
            else:
                flash("Account does not exist. Please register to continue.", category="error")


        return render_template("login.html", user=current_user)

    @app.route("/register", methods=["GET", "POST"])
    def register():
        if request.method == 'POST':
            email = request.form.get('email')
            username = request.form.get('username')
            password1 = request.form.get('password1')
            password2 = request.form.get('password2')

            user = User.query.filter_by(email=email).first()
            if user:
                flash("Email already exists.", category="error")
            elif len(email) < 4:
                flash("Email must be greater than 3 characters.", category="error")
            elif len(username) < 2:
                flash("Username must be greater than 1 character.", category="error")
            elif password1 != password2:
                flash("Passwords do not match! Please try again.", category="error")
            elif len(password1) < 8:
                flash("Password must be greater than 7 characters.", category="error")
            else:
                new_user = User(email=email, username=username, password=generate_password_hash(password1, method='sha256'))
                db.session.add(new_user)
                db.session.commit()
                login_user(new_user, remember=True)
                flash("Account successfully created!", category="success")
                return redirect(url_for('home'))

        return render_template("register.html", user=current_user)

    @app.route("/logout")
    @login_required
    def logout():
        logout_user()
        flash("Logged out succcessfully!", category="success")
        return redirect(url_for('login'))

    @app.route("/selection")
    @login_required
    def selection():
        return render_template("selection.html")

    @app.route("/tutorform", methods=['GET', 'POST'])
    @login_required
    def tutorform():
        if request.method == 'POST':
            tremail = request.form.get('tremail')
            trusername = request.form.get('trusername')
            subjects = request.form.get('subjects')
            session_length = request.form.get('session_length')

            new_tutor = Tutor(user_id=current_user.id, tremail=tremail, trusername=trusername, subjects=subjects, session_length=session_length)
            db.session.add(new_tutor)
            db.session.commit()
            flash('Entry has been saved!', category='success')
            return redirect(url_for("display"))
        
        return render_template("tutorform.html", user=current_user)

    @app.route("/tutoreeform", methods=['GET', 'POST'])
    @login_required
    def tutoreeform():
        if request.method == 'POST':
            flash("Tutoree Entry Successful!", category='success')
            return redirect(url_for("display"))

        return render_template("tutoreeform.html")

    @app.route("/display")
    @login_required
    def display():
        users = Tutor.query.all()

        for user in users:
            print(user.tremail)
            print(user.trusername)
            print(user.subjects)
            print(user.session_length)

        return render_template("display.html", users=users)


    if __name__ == '__main__':
        db.create_all()
        app.run(debug=True)

display.html

{% extends "base.html" %}
{% block title %}SparkWIT | | Available Tutors{% endblock %}

{% block content %}

<center><h1 style="color: beige; background-color: rgba(54, 65, 165, 0.466);"><b><i>Available Tutors</i></b></h1></center>
<table class="table">
    <thead>
      <tr>
        <th scope="col" style="color: beige;"> Tutor Emails</th>
        <th scope="col" style="color: beige;">Username</th>
        <th scope="col" style="color: beige;">Subjects</th>
        <th scope="col" style="color: beige;">Session Length</th>
      </tr>
    </thead>
    {% for user in users.tutors %}
    <tbody>
    <tr>
        <td style="color: beige;">{{ user.tremail }}</td>
        <td style="color: beige;">{{ user.trusername }}</td>
        <td style="color: beige;">{{ user.subjects }}</td>
        <td style="color: beige;">{{ user.session_length }}</td>
    </tr>
    </tbody>
    {% endfor %}
</table>
{% endblock %}

tutorform.html

    {% extends "base.html" %}
    {% block title %}SparkWIT | | Tutor Registration{% endblock %}

    {% block content %}

    <form method="POST">
        <center><h3 style="color: beige; background-color: rgba(54, 65, 165, 0.466);"><i><u>Tutor Entry</u></i></h3></center>
        <div class="form-group">
            <label for="tremail" style="color: azure;"><b>Email</b></label>
            <input 
            type="email"
            class="form-control" 
            id="tremail"
            name="tremail"
            placeholder="[email protected]"
            required />        
        </div>
        <div class="form-group">
            <label for="trusername" style="color: azure;"><b>Username</b></label>
            <input 
            type="text"
            class="form-control" 
            id="trusername" 
            name="trusername"
            placeholder="Username"
            required />        
        </div>
        <div class="form-group">
            <label for="subjects" style="color: azure;"><b>Subject</b></label>
            <input 
            type="text"
            class="form-control" 
            id="subjects" 
            name="subjects"
            placeholder="Ex. AP Physics"
            required />        
        </div>
        <div class="form-group">
            <label for="session_length" style="color: azure;"><b>Session Length</b></label>
            <input 
            type="text"
            class="form-control" 
            id="session_length"
            name="session_length"
            placeholder="Ex. 1.5 hours"
            required />        
        </div>
        <div class="form-group form-check">
            <input type="checkbox" class="form-check-input" id="agree" name="agree" required>
            <label class="form-check-label" for="agree" required><mark>I agree to conduct all sessions virtually for the tutoree's and my safety</mark></label>
        </div>
        <br>
        <button type="submit" class="btn btn-dark">Submit</button>
    </form>

    {% endblock %}
2
  • In the HTML file, shouldn't the loop be like {% for user in users %}? Because that is what you are passing in the render_template as parameter? Commented Apr 2, 2021 at 3:27
  • Oh my goodness. I didn't even realize that! Thank you so much!!! It works now. You are a life saver. Commented Apr 2, 2021 at 3:30

1 Answer 1

1

In the HTML file, the for loop should be like {% for user in users %} because to display the user details, we need to loop on the data item we are passing in the render_template function as parameter.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.