current user.is_authenticated gives me a True value but it didn’t work in base.html file.

huangapple go评论116阅读模式
英文:

current user.is_authenticated gives me a True value but it didn't work in base.html file

问题

以下是您要翻译的内容:

我正在尝试检查用户是否已登录,以更改导航元素并执行其他操作,以下是我的代码

当我执行以下代码时

`print(attempted_account.is_authenticated)` 结果 => `True`

我认为问题可能出在 `base.html` 文件中,所以希望您可以帮助我。

**routs.py:**

    @app.route('/login',methods=['GET','POST'])
    def login():
        form = LoginForm()
        if form.validate_on_submit():
            attempted_account = Account.query.filter_by(email=form.email.data).first()
            print(attempted_account.is_authenticated)
            if attempted_account and attempted_account.check_password(attempted_password=form.password.data):
                login_user(attempted_account)
                flash('登录成功',category='success')
                return redirect(url_for('page',id=1))
            elif not attempted_account:
                flash("该电子邮件不存在",category='danger')
            else:
                flash('密码不正确',category='danger')
        return render_template('login.html',form=form)

**base.html**

    <nav>
        <ul>
            <li><a class="home" href="{{ url_for('home') }}">市场</a></li>
            <li><a href="{{ url_for('page',id=1) }}">购物</a></li> 
        </ul>
        {% if current_user.is_authenticated %}
            <ul>
                <li><a href="#">注销</a></li> 
            </ul>
        {% else %}
            <ul>
                <li><a href="{{ url_for('signup') }}">注册</a></li>
                <li><a href="{{ url_for('login') }}">登录</a></li> 
            </ul>
        {% endif %}
    </nav>

**login.html**

    {% extends 'base.html' %}
    {% block title %}
        登录
    {% endblock %}

    {% block content %}
    <div class="container">
        <form method="POST" class="form-register" style="text-align: center;">
        {{ form.hidden_tag() }}
        {{ form.csrf_token }}

        {{ form.email.label() }}
        {{ form.email(class='form-control',placeholder='example@example.com') }}
        <br>
        {{ form.password.label() }}
        {{ form.password(class='form-control',placeholder='密码') }}
        <br>
        {{ form.submit(class='btn btn-lg btn-block btn-primary') }}
        </form>
    </div>
    {% endblock %}

**请注意,我将我的模型称为 Account 而不是 User**

**编辑:**

这是 models.py:

    from market import db
    from market import bcrypt,login_manager
    from flask_login import UserMixin

    @login_manager.user_loader
    def load_user(user_id):
        return Account.query.filter_by(id=user_id)

    class Account(db.Model,UserMixin):

    id              = db.Column(db.Integer,primary_key = True)
    first_name      = db.Column(db.String(length = 50),nullable  = False)
    last_name       = db.Column(db.String(length = 50),nullable  =False)
    email           = db.Column(db.String(length = 100),nullable =False,unique = True)
    password_hashed = db.Column(db.String(length = 25),nullable = False)
    #country        = db.Column(db.String,nullable = False)
    items           = db.relationship('Item',backref = 'owner',lazy = True)

    @property
    def password(self):
        return self.password
    @password.setter
    def password(self,plain_text_password):
        self.password_hashed = bcrypt.generate_password_hash(plain_text_password).decode('utf-8')
    def check_password(self,attempted_password):
        return bcrypt.check_password_hash(self.password_hashed,attempted_password)
英文:

I'm trying to check if the user is logged in or not to change nav elements and to do more stuff and here is my code

And when I do this

print(attempted_account.is_authenticated) result => True

I think that the problem will be in base.html file so I hope you can help me.

routs.py:

@app.route(&#39;/login&#39;,methods=[&#39;GET&#39;,&#39;POST&#39;])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        attempted_account = Account.query.filter_by(email=form.email.data).first()
        print(attempted_account.is_authenticated)
        if attempted_account and attempted_account.check_password(attempted_password=form.password.data):
            login_user(attempted_account)
            flash(&#39;Success login &#39;,category=&#39;success&#39;)
            return redirect(url_for(&#39;page&#39;,id=1))
        elif not attempted_account:
            flash(&quot;The E-mail doesn&#39;t exist&quot;,category=&#39;danger&#39;)
        else:
            flash(&#39;Tha password is incorrect&#39;,category=&#39;danger&#39;)
    return render_template(&#39;login.html&#39;,form=form)

base.html

&lt;nav&gt;
    &lt;ul&gt;
        &lt;li&gt;&lt;a class=&quot;home&quot; href=&quot;{{ url_for(&#39;home&#39;) }}&quot;&gt;Market&lt;/a&gt;&lt;/li&gt;
        &lt;li&gt;&lt;a href=&quot;{{ url_for(&#39;page&#39;,id=1) }}&quot;&gt;Go shopping&lt;/a&gt;&lt;/li&gt; 
    &lt;/ul&gt;
    {% if current_user.is_authenticated %}
        &lt;ul&gt;
            &lt;li&gt;&lt;a href=&quot;#&quot;&gt;Logout&lt;/a&gt;&lt;/li&gt; 
        &lt;/ul&gt;
    {% else %}
        &lt;ul&gt;
            &lt;li&gt;&lt;a href=&quot;{{ url_for(&#39;signup&#39;) }}&quot;&gt;Sign up&lt;/a&gt;&lt;/li&gt;
            &lt;li&gt;&lt;a href=&quot;{{ url_for(&#39;login&#39;) }}&quot;&gt;Login&lt;/a&gt;&lt;/li&gt; 
        &lt;/ul&gt;
    {% endif %}
&lt;/nav&gt;

login.html

{% extends &#39;base.html&#39; %}
{% block title %}
    Login
{% endblock %}

{% block content %}
&lt;div class=&quot;container&quot;&gt;
    &lt;form method=&quot;POST&quot; class=&quot;form-register&quot; style=&quot;text-align: center;&quot;&gt;
    {{ form.hidden_tag() }}
    {{ form.csrf_token }}

    {{ form.email.label() }}
    {{ form.email(class=&#39;form-control&#39;,placeholder=&#39;example@example.com&#39;) }}
    &lt;br&gt;
    {{ form.password.label() }}
    {{ form.password(class=&#39;form-control&#39;,placeholder=&#39;Password&#39;) }}
    &lt;br&gt;
    {{ form.submit(class=&#39;btn btn-lg btn-block btn-primary&#39;) }}
    &lt;/form&gt;
&lt;/div&gt;
{% endblock %}

Please note that I called my model Account not User

Edit:

Here is models.py:

from market import db
from market import bcrypt,login_manager
from flask_login import UserMixin

@login_manager.user_loader
def load_user(user_id):
    return Account.query.filter_by(id=user_id)

class Account(db.Model,UserMixin):

id              = db.Column(db.Integer,primary_key = True)
first_name      = db.Column(db.String(length = 50),nullable  = False)
last_name       = db.Column(db.String(length = 50),nullable  =False)
email           = db.Column(db.String(length = 100),nullable =False,unique = True)
password_hashed = db.Column(db.String(length = 25),nullable = False)
#country        = db.Column(db.String,nullable = False)
items           = db.relationship(&#39;Item&#39;,backref = &#39;owner&#39;,lazy = True)

@property
def password(self):
    return self.password
@password.setter
def password(self,plain_text_password):
    self.password_hashed = bcrypt.generate_password_hash(plain_text_password).decode(&#39;utf-8&#39;)
def check_password(self,attempted_password):
    return bcrypt.check_password_hash(self.password_hashed,attempted_password)

答案1

得分: 1

问题可能是因为您在user_loader回调中返回了一个查询结果,而不是一个Account对象。

尝试返回Account.query.filter_by(id=user_id).first(),而不是返回Account.query.filter_by(id=user_id)

希望能解决问题。

英文:

The issue is probably because you're returning a query result in the user_loader callback instead of an Account object.

Instead of returning Account.query.filter_by(id=user_id) try returning Account.query.filter_by(id=user_id).first().

Hope it works.

huangapple
  • 本文由 发表于 2023年2月9日 00:20:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75388726.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定