Not getting expected data from SQL Server in Python

Issue

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.

Ive uploaded the code to git:
https://github.com/Desc83/flask_mssql

And it shows like this instead of showing the actual 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 class="jumbotron">
  
  <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 class="jumbotron">
  
  <p>list users</p>
  <ul>
    
    {% for user in users  %}
    <li>{{user}}</li>
    {% endfor %}
    
    {% for item in user %}
    <li>{{item}}</li>
    
    {% endfor %}
  </ul>
</div>
{% endblock %}

Solution

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 %}

Answered By – Mark

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published