I've been following a course, and I want to change my data source from sqlite to mssql.
I've made the connection, and i'm trying to list the users in my db.
But when I do I get the result show below:
<Users 2>
<Users 3>
Instead of showing the actual user data.
import urllib
import os
import pyodbc
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine
from flask import Flask, render_template, url_for, redirect
from flask import Flask
from flask import current_app
app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mssql://@Localhost/FlaskMSSQL?driver=ODBC Driver 17 for SQL Server"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy(app)
Migrate(app,db)
db.init_app(app)
class Users(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer,primary_key= True)
Username = db.Column(db.Text)
Password = db.Column(db.Text)
Email = db.Column(db.Text)
def __init__(self,name):
self.name = name
@app.route('/users')
def listUsers():
users = Users.query.all()
test = Users.
return render_template('listuers.html', users=users)
@app.route('/')
def index():
return render_template('home.html')
if __name__ == '__main__':
app.run(debug=True)
view:
{% extends "base.html" %}
{% block content %}
<div >
<p>list users</p>
<ul>
{% for user in users %}
<li>{{user}}</li>
{% endfor %}
{% for item in user %}
<li>{{item}}</li>
{% endfor %}
</ul>
</div>
{% endblock %}
I have tried to split the data into bits, but it comes with the same result:
{% extends "base.html" %}
{% block content %}
<div >
<p>list users</p>
<ul>
{% for user in users %}
<li>{{user}}</li>
{% endfor %}
{% for item in user %}
<li>{{item}}</li>
{% endfor %}
</ul>
</div>
{% endblock %}
CodePudding user response:
It appears as if you need to specify the __str__
for the Users class.
Alternatively, you can explicitly indicate the fields you want to display in the template.
Instead of this:
{% for user in users %}
<li>{{user}}</li>
{% endfor %}
Try this:
{% for user in users %}
<li>{{user.Username}}</li>
{% endfor %}