B
B
B1ackGh0st2018-06-08 11:05:42
Python
B1ackGh0st, 2018-06-08 11:05:42

How to pass username to template?

Good afternoon. I can’t figure out how to get the user’s name from the table by user id and pass it to the template.

{% for defect in pages.items %}
                <tr>
                  <td>{{ defect.id }}</td>
                  <td>{{ defect.equipment_id }}</td>
                  <td><a href="{{ url_for('defects.defect_detail', id=defect.id) }}">{{ defect.description }}</a></td>
                  <td>{{ defect.author_id }}</td>
                  <td>{{ defect.created }}</td>
                </tr>
              {% endfor %}

class Defect(UserMixin, Equipment, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    equipment_id = db.Column(db.Integer, db.ForeignKey('equipment.id'))
    description = db.Column(db.Text)
    author_id = db.Column(db.Integer, db.ForeignKey('user.id'))
    eliminated = db.Column(db.Integer())
    created = db.Column(db.DateTime, default=datetime.now())  # Дата создания

    def __init__(self, *args, **kwargs):
        super(Defect, self).__init__(*args, **kwargs)
        self.generate_slug()

    def generate_slug(self):
        if self.id:
            self.slug = slugify(self.id)

    def __repr__(self):
        return '<Post id: {}, title: {}>'.format(self.id, self.title)

@login.user_loader
def load_user(id):
    return User.query.get(int(id))

# http://localhost/defects/
@defects.route('/')
def index():

    page = request.args.get('page')
    if page and page.isdigit(): # Если переменная имеет значение и переменная является цифрой
        page = int(page) # Преобразуем переменную в цифру
    else: # Иначе ...
        page = 1 # Даем значение переменной 1

    defects = Defect.query.order_by(Defect.created.desc())

    # пагинация
    pages = defects.paginate(page=page, per_page=5)
    # Выводим шаблон
    return render_template('defects/index.html', defects=defects, pages=pages)


class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(64), index=True, unique=True)
    surname = db.Column(db.String(64), index=True)
    name = db.Column(db.String(64), index=True)
    middle_name = db.Column(db.String(64), index=True)
    password_hash = db.Column(db.String(128))
    role = db.relationship('Role', secondary=roles_users, backref=db.backref('users', lazy='dynamic'))

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
planc, 2018-06-08
@B1ackGh0st

flask-sqlalchemy.pocoo.org/2.3/models/#one-to-many...
in User add
in the
defect.author.name template
and in flask-sqlalchemy.pocoo.org/2.3/quickstart see about joined
While lazy-loading a relationship is fast, it can easily become a major bottleneck when you end up triggering extra queries in a loop for more than a few objects. For this case, SQLAlchemy lets you override the loading strategy on the query level. If you wanted a single query to load all categories and their posts, you could do it like this:
query = Category.query.options(joinedload('posts'))
в class Defect не нужен UserMixin

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question