Flask NameError: имя 'user' не определено - PullRequest
0 голосов
/ 01 июня 2019

У меня есть приложение Flask: enter image description here

Панель пользователя, показывающая, когда пользователь входит в систему, а затем щелкает ссылку поиска в области навигации, должна появиться страница поиска. Когда я нажимаю «Поиск», я получаю «NameError: имя« пользователь »не определен».

Traceback:

NameError
NameError: name 'user' is not defined

Traceback (most recent call last)
File "C:\Users\fbagi\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\fbagi\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\fbagi\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\fbagi\AppData\Roaming\Python\Python37\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\fbagi\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\fbagi\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\fbagi\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\fbagi\AppData\Roaming\Python\Python37\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\fbagi\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\fbagi\AppData\Roaming\Python\Python37\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\fbagi\Documents\GitHub\[edited]\search\views.py", line 32, in search
return render_template('search.html', user=user)
NameError: name 'user' is not defined
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.
To switch between the interactive traceback and the plaintext one, you can click on the "Traceback" headline. From the text traceback you can also create a paste of it. For code execution mouse-over the frame you want to debug and click on the console icon on the right side.

 You can execute arbitrary Python code in the stack frames and there are some extra helpers available for introspection:

dump() shows all variables in the frame
dump(obj) dumps all that's known about the object

search.html:

{% extends "base.html" %} 

{% block title %}{{ user.username }} - Profile{% endblock %} 

{% block header %}<link href="{{ url_for('static', filename='css/base.css') }}" rel="stylesheet">{% endblock %}

{% block content %} 

{% include "navbar.html" %}

<div class="row">

<div class="col-md-3">
<body>

<form action="{{url_for('search_app.search')}}" method="POST">
    <input type="text" name="SearchForm">
<p>        <input type="submit" name="my-form" value="Send"></p>
</form>
{{ results }}
</body>

{% endblock %}

поиск / views.py

from flask import Blueprint
from flask import Flask, request, render_template, jsonify, url_for, redirect, request
import operator
from search.forms import SearchForm
from user.models import User

search_app = Blueprint('search_app', __name__)
@search_app.route('/search', methods = ['GET', 'POST'])
def search():
    form = SearchForm()
    return render_template('search.html', user=user)

Я попытался определить переменную user , включив в views.py :

user = User.objects.filter(username=session.get('username')).first()

... но все равно возникает та же проблема.

Когда я экспортирую объект User во время выполнения, все проверяется:

 >>> from user.models import User
 >>> User
 <class 'user.models.User'>

Что я делаю не так?

1 Ответ

0 голосов
/ 04 июня 2019

Вам необходимо передать действительный экземпляр класса User.Примерно так -

def search():
    form = SearchForm()
    user = User.objects.filter(username=session.get('username')).first()
    return render_template('search.html', user=user)

Для аутентификации с использованием фляги вы можете обратиться по ссылкам ниже

...