UndefinedError: current_user is undefined

2024/10/1 17:38:01

I have a app with flask which works before But Now I use Blueprint in it and try to run it but got the error so i wonder that is the problem Blueprint that g.user Not working? and how can I fix it Thnx :)

app/layout/__ init __.py :

from flask import Blueprint
layout = Blueprint('layout', __name__)
from . import view

__ init __ .py

from flask import Flask
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
import psycopg2
from config import basedir
from config import configapp = Flask(__name__)
app.config.from_object('config')
db = SQLAlchemy()
lm = LoginManager()
lm.init_app(app)
lm.login_view = 'login'def create_app(config_name):app = Flask(__name__)app.config['DEBUG'] = Trueapp.config.from_object(config[config_name])db.init_app(app)from .layout import layout as appr_blueprint# register our blueprintsapp.register_blueprint(appr_blueprint)return app

view.py:

@layout.before_request def before_request():g.user = current_user @layout.route('/login', methods = ['GET', 'POST']) def login():form = LoginForm()#checks if the user is authernticated#or not, if yes it skips authentfic.if current_user is not None and current_user.is_authenticated():return redirect(url_for('user'))#does not allow user to use get methodif request.method == 'GET':return render_template('login.html',form = form,title = 'Login')#taking the user submitted data and checking if it exists in the databaseuser_in_db = User.query.filter_by(name=form.name.data.lower()).first()#if the username is not wrongif user_in_db is not None and user_in_db != False:if form.email.data !=  user_in_db.email:flash('Email is incorrect')return redirect(url_for('login'))login_user(user_in_db)return redirect(url_for('user',page=1,sortby='normal'))else:flash('Username does not exists')return render_template('login.html',form = form,title = 'Login')

base.html:

<div id="bodyAll"><div class="navbar navbar-inverse navbar-fixed-top"><div class="container-fluid"><ul class="nav navbar-nav"><li id="logo"><a href="{{ url_for('layout.home') }}"><span id="globe"class="glyphicon glyphicon-home"></span>Home</a></li><li id="logo"><a href="{{ url_for('layout.new') }}"><span id="globe"class="glyphicon glyphicon-plus"></span>Add Monkey</a></li><li><a href="{{ url_for('layout.user',page = '1', sort = 'normal', monkey = monkey) }}"><span class="glyphicon glyphicon-tree-deciduous"></span>Jungle</a></li>{% if current_user.is_authenticated() %} //**Got error here**<li><a href="#"><span class="glyphicon glyphicon-user"></span>{{g.user.name.capitalize()}}</a></li>{% endif %}
Answer

you should register login_manager in init.py try to add this

login_manager.init_app(app)
https://en.xdnf.cn/q/70948.html

Related Q&A

Scipy filter with multi-dimensional (or non-scalar) output

Is there a filter similar to ndimages generic_filter that supports vector output? I did not manage to make scipy.ndimage.filters.generic_filter return more than a scalar. Uncomment the line in the cod…

How do I stop execution inside exec command in Python 3?

I have a following code:code = """ print("foo")if True: returnprint("bar") """exec(code) print(This should still be executed)If I run it I get:Tracebac…

sqlalchemy concurrency update issue

I have a table, jobs, with fields id, rank, and datetime started in a MySQL InnoDB database. Each time a process gets a job, it "checks out" that job be marking it started, so that no other p…

Python matplotlib: Change axis labels/legend from bold to regular weight

Im trying to make some publication-quality plots, but I have encountered a small problem. It seems by default that matplotlib axis labels and legend entries are weighted heavier than the axis tick mark…

Negative extra_requires in Python setup.py

Id like to make a Python package that installs a dependency by default unless the user specially signals they do not want that.Example:pip install package[no-django]Does current pip and setup.py mechan…

Get Type in Robot Framework

Could you tell me about how to get the variable type in Robot Framework.${ABC} Set Variable Test ${XYZ} Set Variable 1233Remark: Get the variable Type such as string, intget ${ABC} type = strin…

Keras 2, TypeError: cant pickle _thread.lock objects

I am using Keras to create an ANN and do a grid search on the network. I have encountered the following error while running the code below:model = KerasClassifier(build_fn=create_model(input_dim), verb…

How to remove minimize/maximize buttons while preserving the icon?

Is it possible to display the icon for my toplevel and root window after removing the minimize and maximize buttons? I tried using -toolwindow but the icon cant be displayed afterwards. Is there anoth…

Undefined reference to `PyString_FromString

I have this C code:... [SNIP] ... for(Node = Plugin.Head; Node != NULL; Node = Node->Next) {//Create new python sub-interpreterNode->Interpreter = Py_NewInterpreter();if(Node->Interpreter == N…

How to call a method from a different blueprint in Flask?

I have an application with multiple blueprinted modules.I would like to call a method (a route) that would normally return a view or render a template, from within a different blueprints route.How can …