I'm new to Flask and JS, so I'm really not sure what the problem is here.
app.py
#app.route('/email', methods=["GET", "POST"])
def email():
email_form = EmailForm(csrf_enabled=False)
return render_template("email-form.html", template_form=email_form, action='/appliance2', method='POST')
forms.py (I created that validator using the template from the wtForms docs)
class DBPresenceCheck(object):
def __init__(self, table, message="Field is invalid"):
self.table = table
self.message = message
def __call__(self, form, field):
presence = Connector().query('SELECT 1 FROM %(table)s WHERE %(col_name)s = %(data)s LIMIT 1;',
{'col_name': field.label, 'data': field.data, 'table': self.table})
if presence == 1:
raise ValidationError(self.message)
class EmailForm(FlaskForm):
title = "Enter Household Info"
subtitle = "Please enter your email address:"
email_input = StringField("email", validators=[email(),
DBPresenceCheck('Household', 'That email is already present in the database.')])
# print(email_input.data)
submit = SubmitField("Submit")
email-form.html
{% extends "base.html" %}
{% block content%}
<div class="container py-4">
<div class="p-5 mb-4 bg-light rounded-3">
<h2 class="display-5 fw-bold">{{ template_form.title }}</h2>
<p class="col-md-8 fs-4">{{ template_form.subtitle }}</p>
<form action="{{ action }}" method="{{ method }}">
<div id="main_elements">
{{ template_form['email_input']() }}
</div>
<div id="submit_element">
<br>
{{ template_form["submit"](class_="btn btn-primary") }}
</div>
</form>
</div>
</div>
{%endblock%}
I first realized something was wrong when I was testing the validation, and neither validator ever threw. I added the print statement in forms, and now, when I use flask run, I get the following error.
Traceback (most recent call last):
File "C:\Languages\Python\3.9\lib\runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Languages\Python\3.9\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\Scripts\flask.exe\__main__.py", line 7, in <module>
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 1047, in main
cli.main()
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 1055, in main
rv = self.invoke(ctx)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 1657, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 1404, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\decorators.py", line 84, in new_func
return ctx.invoke(f, obj, *args, **kwargs)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\click\core.py", line 760, in invoke
return __callback(*args, **kwargs)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 911, in run_command
raise e from None
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 897, in run_command
app = info.load_app()
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 312, in load_app
app = locate_app(import_name, None, raise_if_not_found=False)
File "C:\Users\askat\.virtualenvs\askat-YHGTcgZo\lib\site-packages\flask\cli.py", line 218, in locate_app
__import__(module_name)
File "C:\Users\askat\PycharmProjects\cs6400-2022-03-Team060\Phase_3\app.py", line 4, in <module>
from forms import *
File "C:\Users\askat\PycharmProjects\cs6400-2022-03-Team060\Phase_3\forms.py", line 33, in <module>
class EmailForm(AddForm):
File "C:\Users\askat\PycharmProjects\cs6400-2022-03-Team060\Phase_3\forms.py", line 37, in EmailForm
print(email_input.data)
AttributeError: 'UnboundField' object has no attribute 'data'
If the print statement is just print(email_input), then when I run it, the following output
<UnboundField(StringField, ('email',), {'validators': [<wtforms.validators.Email object at 0x0000024145A4F460>, <forms.DBPresenceCheck object at 0x0000024145A4F610>]})>
but no errors are thrown. It seems strange to me that the error is thrown before the field is even created.
In the validators list you need to pass in an instance of class Email. So you field should read:
from wtforms.validators import Email
email_input = StringField("email", validators=[Email(), ...
and don't forget to install the email package as Flask-WTF doesn't include anymore the Email in their validators.
Related
I am using flask_babel for localization of a python project.
When extracting translatable strings from templates, which is put in {{ _('') }} , i am getting the following error. If anyone of you can solve it, please share the solution here. thanks in advance.
Traceback (most recent call last):
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 2069, in __call__
return self.wsgi_app(environ, start_response)
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 2054, in wsgi_app
response = self.handle_exception(e)
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 2051, in wsgi_app
response = self.full_dispatch_request()
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 1501, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 1499, in full_dispatch_request
rv = self.dispatch_request()
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/app.py", line 1485, in dispatch_request
return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
File "/mnt/c/Users/Lungsang/Desktop/new-pyrrha/pyrrha/app/main/views/index.py", line 34, in index
return render_template_with_nav_info('main/index.html')
File "/mnt/c/Users/Lungsang/Desktop/new-pyrrha/pyrrha/app/main/views/utils.py", line 60, in render_template_with_nav_info
return render_template(template, **kwargs)
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/templating.py", line 147, in render_template
return _render(
File "/home/lungsang/.local/lib/python3.8/site-packages/flask/templating.py", line 128, in _render
rv = template.render(context)
File "/home/lungsang/.local/lib/python3.8/site-packages/jinja2/environment.py", line 1289, in render
self.environment.handle_exception()
File "/home/lungsang/.local/lib/python3.8/site-packages/jinja2/environment.py", line 924, in handle_exception
raise rewrite_traceback_stack(source=source)
File "/mnt/c/Users/Lungsang/Desktop/new-pyrrha/pyrrha/app/templates/main/index.html", line 1, in top-level template code
{% extends 'layouts/base.html' %}
File "/mnt/c/Users/Lungsang/Desktop/new-pyrrha/pyrrha/app/templates/layouts/base.html", line 36, in top-level template code
{% block content %}{% endblock %}
File "/mnt/c/Users/Lungsang/Desktop/new-pyrrha/pyrrha/app/templates/main/index.html", line 5, in block 'content'
<h1>{{ _('Welcome to Pyrrha !') }}</h1>
File "/home/lungsang/.local/lib/python3.8/site-packages/jinja2/utils.py", line 81, in from_obj
if hasattr(obj, "jinja_pass_arg"):
jinja2.exceptions.UndefinedError: '_' is undefined
#MAIN APP FILE
from flask_login import current_user
from flask import request , Flask
from flask_babel import Babel
from .utils import render_template_with_nav_info
from .. import main
from ...models import Corpus
from ...utils.pagination import int_or
app = Flask(__name__)
app.config['BABEL_DEFAULT_LOCALE'] = 'en'
babel = Babel(app)
#babel.localeselector
def get_locale():
#return request.accept_languages.best_match(['es', 'fr', 'en'])
return 'bo_CN'
#main.route('/')
def index():
if current_user.is_authenticated and not
current_user.is_anonymous:
corpora = Corpus.for_user(current_user, _all=False).paginate(
page=int_or(request.args.get("page"), 1),
per_page=20 # ToDo: Should it be hardcoded ?
)
return render_template_with_nav_info("main/index_loggedin.html", corpora=corpora)
return render_template_with_nav_info('main/index.html')
TEMPLATE FILE (index.html)
{% extends 'layouts/base.html' %}
{% block content %}
<div class="ui text container">
<h1>{{ _('Welcome to Pyrrha !') }}</h1>
<p>Pyrrha is a simple Python Flask WebApp to fasten the post-correction of lemmatized and morpho-syntactic tagged corpora.</p>
<p>It is under active development at the École Nationale des Chartes and can
be found on github.</p>
<p>To cite it in a paper, please use the information available on Zenodo</p>
</div>
{% endblock %}
After applying the following codes in init.py module, its working fine. Thank you
babel = Babel(app)
#babel.localeselector
def get_locale():
return 'es'
remove the "_" in the h1 tag in the template's file
I would like to show a table on a website using Google Cloud SQL and Google App Engine.
I am using Flask and pymysql. To show the result of my query I use the render_template of Flask.
I already found other similar topics here (like Topic: Listing table results to HTML with Flask), but I still get an error when I deploy my app. It seems that the error has to do with the for loop.. The error says "jinja2.exceptions.TemplateSyntaxError: tag name expected".
Here's the full error message I get:
ERROR in app: Exception on /analysis [GET]
Traceback (most recent call last): File "/env/lib/python3.7/site-packages/flask/app.py", line 2292, in wsgi_app response = self.full_dispatch_request()
File "/env/lib/python3.7/site-packages/flask/app.py", line 1815, in full_dispatch_request rv = self.handle_user_exception(e)
File "/env/lib/python3.7/site-packages/flask/app.py", line 1718, in handle_user_exception reraise(exc_type, exc_value, tb)
File "/env/lib/python3.7/site-packages/flask/_compat.py", line 35, in reraise raise value
File "/env/lib/python3.7/site-packages/flask/app.py", line 1813, in full_dispatch_request rv = self.dispatch_request()
File "/env/lib/python3.7/site-packages/flask/app.py", line 1799, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args)
File "/srv/main.py", line 61, in analysis return render_template("analysis.html", result = result)
File "/env/lib/python3.7/site-packages/flask/templating.py", line 134, in render_template return _render(ctx.app.jinja_env.get_or_select_template(template_name_or_list), File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 869, in get_or_select_template return self.get_template(template_name_or_list, parent, globals)
File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 830, in get_template return self._load_template(name, self.make_globals(globals))
File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 804, in _load_template template = self.loader.load(self, name, globals)
File "/env/lib/python3.7/site-packages/jinja2/loaders.py", line 125, in load code = environment.compile(source, name, filename)
File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 591, in compile self.handle_exception(exc_info, source_hint=source_hint)
File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 780, in handle_exception reraise(exc_type, exc_value, tb)
File "/env/lib/python3.7/site-packages/jinja2/_compat.py", line 37, in reraise raise value.with_traceback(tb)
File "/srv/templates/analysis.html", line 23, in template <p class="p1"><span class="s1"><span class="Apple-tab-span"> </span>{% </span><span class="s2">for</span><span class="s1"> r </span><span class="s2">in</span><span class="s1"> result %}</span></p>
File "/env/lib/python3.7/site-packages/jinja2/environment.py", line 497, in _parse return Parser(self, source, name, encode_filename(filename)).parse()
File "/env/lib/python3.7/site-packages/jinja2/parser.py", line 901, in parse result = nodes.Template(self.subparse(), lineno=1)
File "/env/lib/python3.7/site-packages/jinja2/parser.py", line 883, in subparse rv = self.parse_statement()
File "/env/lib/python3.7/site-packages/jinja2/parser.py", line 125, in parse_statement self.fail('tag name expected', token.lineno)
File "/env/lib/python3.7/site-packages/jinja2/parser.py", line 59, in fail raise exc(msg, lineno, self.name, self.filename) jinja2.exceptions.TemplateSyntaxError: tag name expected
My Code in main.py:
import logging
import os
from flask import Flask, render_template
from flask import request
import urllib.request
from urllib.parse import parse_qs, urlparse
import platform
import pymysql
import datetime
db_user = os.environ.get('CLOUD_SQL_USERNAME')
db_password = os.environ.get('CLOUD_SQL_PASSWORD')
db_name = os.environ.get('CLOUD_SQL_DATABASE_NAME')
db_connection_name = os.environ.get('CLOUD_SQL_CONNECTION_NAME')
app = Flask(__name__)
#app.route('/analysis', methods=['GET'])
def analysis():
if os.environ.get('GAE_ENV') == 'standard':
unix_socket = '/cloudsql/{}'.format(db_connection_name)
cnx = pymysql.connect(user=db_user, password=db_password,
unix_socket=unix_socket, db=db_name)
else:
host = '127.0.0.1'
#unix_socket = '/cloudsql/{}'.format(db_connection_name)
cnx = pymysql.connect(user=db_user, password=db_password,
unix_socket=unix_socket, db=db_name)
with cnx.cursor() as cursor:
sql = 'SELECT * FROM content'
cursor.execute(sql)
result = cursor.fetchall()
cnx.close()
return render_template("analysis.html", result = result)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=8080, debug=True)
File analysis.html:
<!doctype html>
<table>
<tr>
<th>contentID</th>
<th>timestamp</th>
<th>clientID</th>
<th>content</th>
</tr>
{% for r in result %}
<tr>
<td>{{ r[0] }}</td>
<td>{{ r[1] }}</td>
<td>{{ r[2] }}</td>
<td>{{ r[3] }}</td>
</tr>
{% endfor %}
</table>
Do you have any suggestions what I can can change to make it work?
Thanks in advance!
One way you can do this is by first have an object, or use pandas to read_csv and then use the dataframe's to_html method.
This saves a ton of time if your data is already formatted correctly:
import pandas as pd
from flask import Flask, render_template
#app.route("/table-page", methods=['GET'])
def table():
data_dic = {
'id': [100, 101, 102],
'color': ['red', 'blue', 'red']}
columns = ['id', 'color']
index = ['a', 'b', 'c']
df = pd.DataFrame(data_dic, columns=columns, index=index)
table = df.to_html(index=False)
return render_template(
"at-leaderboard.html",
table=table)
Now you take the HTML string and paste it into you template without send it as JSON or a dict needing Jinja template formating:
<html>
<body>
<div>
{{ table | safe }}
</div>
</body>
</html>
Based on the stack trace, the text editor you're using for analysis.html isn't a plain text editor. It's saving the file in some other format, making it invalid Jinja2 syntax.
So this line that you see in your editor:
{% for r in result %}
Python will see as (based on the stack trace; added some line breaks for clarity):
<p class="p1">
<span class="s1">
<span class="Apple-tab-span">
</span>
{% </span><span class="s2">for</span><span class="s1"> r </span><span class="s2">in</span><span class="s1"> result %}
</span>
</p>
To fix the problem, open the file analysis.html in a plain text editor and edit it as needed.
{% for r in result %}
<p class="p1">
<span class="s1">
<span class="Apple-tab-span">
</span>
</span><span class="s2">for</span><span class="s1"> {{ r }}</span><span class="s2">in</span><span class="s1">
</span>
</p>
{% endfor %}
Using django. I have the following model:
class Postagem(models.Model):
id = models.AutoField(primary_key=True, editable=False)
descricao = models.CharField(max_length=50)
area = models.ForeignKey('core.Area', null=True)
user = models.ForeignKey('User')
categoria = models.CharField(max_length=50, null=True)
post = models.FileField(upload_to='posts/', null=True)
thumbnail = models.FileField(upload_to='posts/', null=True)
def __str__(self):
return self.descricao
The Following form:
class PostForm(forms.ModelForm):
categoria = forms.ChoiceField(choices=[("Video","Vídeo"),("Audio","Aúdio"),("Imagem","Imagem"),("Musica","Música")], required=True)
thumbnail = forms.FileField(required=False)
class Meta:
model = Postagem
fields = ['descricao', 'area', 'user', 'post']
View:
def profileView(request):
context = getUserContext(request)
if request.method == 'POST':
exception=None
userDict = {}
userDict["user"] = context["user"].id
if "categoria" in request.POST:
newPost = request.POST.copy()
newPost.update(userDict)
form = PostForm(newPost,request.FILES)
print("postform POST: ",newPost, " File ",request.FILES)
if form.is_valid():
print("valid")
try:
form.save()
print("saved")
return HttpResponseRedirect(reverse_lazy('accounts:profile'))
except IntegrityError as e:
print("Integrity Error")
exception=e
else:
print("PostForm error")
print(form.errors)
form.non_field_errors=form.errors
if exception is not None:
form.non_field_errors.update(exception)
context['form']=form
posts = Postagem.objects.get_queryset().order_by('id')
paginator = Paginator(posts, 12)
page = request.GET.get('page')
context["areas"] = Area.objects.all()
try:
posts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
posts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
posts = paginator.page(paginator.num_pages)
context["posts"]=posts
return render(
request,
'accounts/profile.html',
context
)
And at last the template:
{% for post in posts %}
{% if forloop.counter0|divisibleby:4 or forloop.counter0 == 0 %}
<div id="grid-profile" class="row grid">
<div class="col-md-1"></div>
{% endif %}
{% ifnotequal post.categoria "Imagem"%}
<iframe id=post{{forloop.counter}} width="420" height="315"
src={{post.post.url}}>
</iframe>
{% else %}
<div class="col-md-2">
<button type="button" id="modal1trigger" data-toggle="modal" data-target="#modal1"><img class="img-responsive" src={{post.post.url}}></img></button>
</div>
{% endifnotequal %}
{% if forloop.counter|divisibleby:4 or forloop.counter == posts|length %}
<div class="col-md-1"></div>
</div>
{% endif %}
{% endfor %}
<div class="pagination">
<span class="step-links">
{% if posts.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ posts.number }} of {{ posts.paginator.num_pages }}.
</span>
{% if posts.has_next %}
next
{% endif %}
</span>
</div>
I cut some of the template... Anyways, I want to be able to add all kinds of posts. Songs, Videos, Images, Docs, etc. And it IS working. The posts are being added. But, I'm having a recurring error and I don't know why. That could be very dangerous so I started looking into it, but with no luck in finding an acceptable answer. The error only happens when trying to get a song or a video.
[21/Sep/2017 23:32:44] "GET /media/posts/13567830_1641362072853439_1924036772_n.mp4 HTTP/1.1" 200 1171456
Traceback (most recent call last):
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 138, in run
self.finish_response()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
self.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 279, in write
self._write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 453, in _write
result = self.stdout.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 775, in write
self._sock.sendall(b)
ConnectionResetError: [WinError 10054] Foi forçado o cancelamento de uma conexão existente pelo host remoto
[21/Sep/2017 23:32:44] "GET /media/posts/13567830_1641362072853439_1924036772_n.mp4 HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 53113)
Traceback (most recent call last):
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 138, in run
self.finish_response()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
self.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 279, in write
self._write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 453, in _write
result = self.stdout.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 775, in write
self._sock.sendall(b)
ConnectionResetError: [WinError 10054] Foi forçado o cancelamento de uma conexão existente pelo host remoto
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 141, in run
self.handle_error()
File "C:\Users\eduardo\Envs\ProExC\lib\site-packages\django\core\servers\basehttp.py", line 88, in handle_erro
r
super(ServerHandler, self).handle_error()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 368, in handle
_error
self.finish_response()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
self.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 274, in write
self.send_headers()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 331, in send_h
eaders
if not self.origin_server or self.client_is_modern():
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 344, in client
_is_modern
return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 639, in process_re
quest_thread
self.finish_request(request, client_address)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 361, in finish_req
uest
self.RequestHandlerClass(request, client_address, self)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 696, in __init__
self.handle()
File "C:\Users\eduardo\Envs\ProExC\lib\site-packages\django\core\servers\basehttp.py", line 155, in handle
handler.run(self.server.get_app())
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 144, in run
self.close()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\simple_server.py", line 35, in cl
ose
self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
----------------------------------------
[21/Sep/2017 23:32:44] "GET /media/posts/03_-_The_Mute.mp3 HTTP/1.1" 200 1179648
Traceback (most recent call last):
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 138, in run
self.finish_response()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
self.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 279, in write
self._write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 453, in _write
result = self.stdout.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 775, in write
self._sock.sendall(b)
ConnectionResetError: [WinError 10054] Foi forçado o cancelamento de uma conexão existente pelo host remoto
[21/Sep/2017 23:32:44] "GET /media/posts/03_-_The_Mute.mp3 HTTP/1.1" 500 59
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 53114)
Traceback (most recent call last):
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 138, in run
self.finish_response()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
self.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 279, in write
self._write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 453, in _write
result = self.stdout.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 775, in write
self._sock.sendall(b)
ConnectionResetError: [WinError 10054] Foi forçado o cancelamento de uma conexão existente pelo host remoto
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 141, in run
self.handle_error()
File "C:\Users\eduardo\Envs\ProExC\lib\site-packages\django\core\servers\basehttp.py", line 88, in handle_erro
r
super(ServerHandler, self).handle_error()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 368, in handle
_error
self.finish_response()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 180, in finish
_response
self.write(data)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 274, in write
self.send_headers()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 331, in send_h
eaders
if not self.origin_server or self.client_is_modern():
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 344, in client
_is_modern
return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
TypeError: 'NoneType' object is not subscriptable
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 639, in process_re
quest_thread
self.finish_request(request, client_address)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 361, in finish_req
uest
self.RequestHandlerClass(request, client_address, self)
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\socketserver.py", line 696, in __init__
self.handle()
File "C:\Users\eduardo\Envs\ProExC\lib\site-packages\django\core\servers\basehttp.py", line 155, in handle
handler.run(self.server.get_app())
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\handlers.py", line 144, in run
self.close()
File "c:\users\eduardo\appdata\local\programs\python\python36-32\Lib\wsgiref\simple_server.py", line 35, in cl
ose
self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
---------------------------------------
Edit:
Using Django 1.11.3,
Windows 10,
Tested with Opera and Chrome,
Running server using gulp
**Edit 2: **
Hey, the error ONLY HAPPENS if there is a iframe tag in the html!!
It appears that its a python error:
Django ticket: https://code.djangoproject.com/ticket/26995
Python ticket: https://bugs.python.org/issue14574
Didn't managed to solve just yet, if I can I will edit this answer explaining in detail how to solve it.
Edit
It seems to be a error on chrome. It didn't come to me, 'cause I was using Opera, but opera uses chromium as well. In internet explorer the error didn't show.
https://code.djangoproject.com/ticket/21227#no1
This is the bug tracker
the first error
self.environ['SERVER_PROTOCOL'].upper() is failing because self.environ['SERVER_PROTOCOL'] is None, and you can't do None.upper() you can only do .upper() on strings (as far as i'm aware).
the second error
self.status.split(' ',1)[0], self.bytes_sent
AttributeError: 'NoneType' object has no attribute 'split'
This is failing because you self.status is None and you can't do None.split(), again this should be a string.
So it looks like some of the required values for these classes aren't being initialised or passed through.
It looks like the issue is with Django.core and WSGIref, so either the configuration isn't correct or perhaps there's an issue with the version you have installed?
Which version of Django are you running?
Also are you running the server from ./manage.py runserver ?
[update 2017-09-28]
There's a couple of things I've modified, to start with I'm not copying the request.POST to a new dict, before passing it, this could be the cause of some of the values disappearing when trying to process a post.
I'm also passing user as a kwarg to your form, rather than trying to inject it into the copied POST.
mostly I've just updated some of the code to be a little easier to read, let's see how that goes.
# forms.py
class PostForm(forms.ModelForm):
categoria = forms.ChoiceField(choices=[("Video","Vídeo"),("Audio","Aúdio"),("Imagem","Imagem"),("Musica","Música")], required=True)
thumbnail = forms.FileField(required=False)
class Meta:
model = Postagem
fields = ['descricao', 'area', 'user', 'post']
def __init__(self, *args, **kwargs): # handle user kwarg
if 'user' in kwargs.keys():
self.user = kwargs.pop('user')
super(PostForm, self).__init__(*args, **kwargs)
# views.py
def profileView(request):
form = None
if request.method == 'POST':
exception=None
if "categoria" in request.POST:
if request.user:
form = PostForm(request.POST,request.FILES, user=request.user) # pass user as a kwarg
print("postform POST: ",newPost, " File ",request.FILES)
if form.is_valid():
print("valid")
try:
form.save()
print("saved")
return HttpResponseRedirect(reverse_lazy('accounts:profile'))
except IntegrityError as e:
print("Integrity Error")
exception=e
else:
print("PostForm error")
print(form.errors)
#form has been indented as previously it would have been called before being initialised
form.non_field_errors=form.errors
if exception is not None:
form.non_field_errors.update(exception)
posts = Postagem.objects.get_queryset().order_by('id')
paginator = Paginator(posts, 12)
page = None
if request.GET:
page = request.GET.get('page')
areas = Area.objects.all()
try:
posts = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
posts = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
posts = paginator.page(paginator.num_pages)
#return values
return render(
request,
'accounts/profile.html',
{
'form': form,
'areas': areas,
'posts': posts,
}
)
Are you using PostgreSQL? It could be caused by a code page error.
C:\>psql -U postgres
psql (10.5)
WARNING: Console code page (850) differs from Windows code page (1252)
8-bit characters might not work correctly. See psql reference
page "Notes for Windows users" for details.
Type "help" for help.
postgres=#
Trying setting the code page before you start Django.
cmd.exe /c chcp 1252
I'm trying to make a flask app on google app engine which shows database entries on their own page.
This is a bit of my views.py code:
#app.route('/posts/<int:id>')
def display_post(id):
post = Post.filter('id =', id)
return render_template('display_post.html', post=post)
Then my display_posts.html
{% extends "base.html" %}
{% block content %}
<ul>
<h1 id="">Post</h1>
<li>
{{ posts.title }}<br />
{{ posts.content }}
</li>
</ul>
{% endblock %}
Now when I have a post with ID 5700305828184064 and visit this page I should see the title and content:
www.url.com/posts/5700305828184064
However I get this traceback:
<type 'exceptions.AttributeError'>: type object 'Post' has no attribute 'filter'
Traceback (most recent call last):
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/main.py", line 4, in <module>
run_wsgi_app(app)
File "/base/data/home/runtimes/python/python_lib/versions/1/google/appengine/ext/webapp/util.py", line 99, in run_wsgi_app
run_bare_wsgi_app(add_wsgi_middleware(application))
File "/base/data/home/runtimes/python/python_lib/versions/1/google/appengine/ext/webapp/util.py", line 117, in run_bare_wsgi_app
result = application(env, _start_response)
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/flask/app.py", line 874, in __call__
return self.wsgi_app(environ, start_response)
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/flask/app.py", line 864, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/flask/app.py", line 861, in wsgi_app
rv = self.dispatch_request()
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/flask/app.py", line 696, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/base/data/home/apps/s~smart-cove-95709/1.384741962561717132/blog/views.py", line 25, in display_post
post = Post.filter('id =', id)
How can I show the title and content of the entry for a given ID?
You need to create a query object first, then apply the filter to that.
q = Post.all()
post = q.filter("id =", id)
This is the first example in the GAE docs on queries.
Also, your template references the name posts, but you've passed in the name post. Change your template appropriately.
I have a settings page which has two forms for handling the settings for two different Models. The Profile model form works. The Chef model form doesn't. The form fails gracefully, and isn't throwing a Django error page - so in using pdb, I found the form is not valid, and is throwing a Syntax Error.
I'm confused as to which field this error is coming form. Any help would be greatly appreciated. Thanks!
Error:
*** SyntaxError: SyntaxError('unexpected EOF while parsing', ('<string>', 0, 0, ''))
HTML
{% if form.is_multipart %}
<form enctype="multipart/form-data" method="post" action=".">{% csrf_token %}
{% else %}
<h3>Profile Settings</h3>
<form method="post" action=".">
{% endif %}
<dl>
<dt>{{form.photo.label}}</dt>
<dd>{{form.photo}}</dd>
<dt>{{form.firstname.label}}</dt>
<dd>{{form.firstname}}</dd>
<dt>{{form.lastinitial.label}}</dt>
<dd>{{form.lastinitial}}</dd>
</dl>
<button type="submit">Save</button>
</form>
<h3>Chef Settings</h3>
<form action="{% url edit_chef chef.id %}" method="post" accept-charset="utf-8">{% csrf_token %}
<dl>
<dt>{{chefform.category.label}}</dt>
<dd>{{chefform.category}}</dd>
<dt>{{chefform.price.label}}</dt>
<dd>{{chefform.price}}</dd>
<dt>{{chefform.meal.label}}</dt>
<dd>{{chefform.meal}}</dd>
<dt>{{chefform.language.label}}</dt>
<dd>{{chefform.language}}</dd>
<dt>{{chefform.address.label}}</dt>
<dd>{{chefform.address}}</dd>
<dt>{{chefform.neighborhood.label}}</dt>
<dd>{{chefform.neighborhood}}</dd>
<dt>{{chefform.city.label}}</dt>
<dd>{{chefform.city}}</dd>
<dt>{{chefform.state.label}}</dt>
<dd>{{chefform.state}}</dd>
<dt>{{chefform.menu.label}}<span id="rBann" class="minitext">1000</span></dt>
<dd>{{chefform.menu}}</dd>
</dl>
<button type="submit">Save</button>
</form>
Chef Form
class ChefForm(forms.ModelForm):
class Meta:
model = Chef
fields = ('category','meal','price','language','address','neighborhood','city','state', 'country', 'menu')
category = forms.ChoiceField(
label=_("Food style"),
choices=([('Afghan','Afghan'),('African','African'),('American','American'),]),
required=True)
meal = forms.ModelMultipleChoiceField(
label=_("What is your best meal?"),
queryset=Meal.objects.all(),
required=True)
price = forms.IntegerField(
label=_("Price per person"),
widget=forms.TextInput(),
required=True)
language = forms.ModelMultipleChoiceField(
label=_("Languages spoken"),
queryset=Language.objects.all(),
required=True)
address = forms.CharField(
label=_("Your Address"),
widget=forms.TextInput(),
required=True)
neighborhood = forms.CharField(
label=_("Your Neighborhood"),
widget=forms.TextInput(),
required=True)
city = forms.CharField(
label=_("Your City"),
widget=forms.TextInput(),
required=True)
state = forms.CharField(
label=_("Your state"),
widget=forms.TextInput(),
required=True)
country = forms.CharField(
label=_("Your country"),
widget=forms.TextInput(),
required=True)
menu = forms.CharField(
label=_("What's unique about your cooking & home? Pets? Have a family or roommates?"),
widget=forms.TextInput(),
required=True)
def __init__(self, *args, **kwargs):
super(ChefForm, self).__init__(*args, **kwargs)
self.fields['price'].widget.attrs = {
'placeholder':'10'}
self.fields['menu'].widget.attrs = {
'placeholder':'Tacos!'}
View:
#login_required
def edit_chef(request, chef_id, template_name="chef/newchef.html"):
chef = get_object_or_404(Chef, id=chef_id)
if request.user != chef.cook:
return HttpResponseForbidden()
if request.method == 'POST':
import pdb; pdb.set_trace()
chefform = ChefForm(request.POST, instance=chef)
if chefform.is_valid():
chefform.save()
return HttpResponseRedirect('/users/%d/' % request.user.id)
else:
return HttpResponseRedirect('/users/%d/' % request.user.id)
data = { "chef":chef,
"chefform":chefform }
return render_to_response(template_name,
data,
context_instance=RequestContext(request))
To add more information to this bug, I was able to pull up this broken pipe error:
[29/Jan/2011 09:20:24] "POST /chef/1/edit/ HTTP/1.1" 200 104804
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 281, in run
self.finish_response()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 321, in finish_response
self.write(data)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 400, in write
self.send_headers()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 464, in send_headers
self.send_preamble()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 382, in send_preamble
'Date: %s\r\n' % http_date()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 322, in write
self.flush()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 301, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
----------------------------------------
Exception happened during processing of request from ('127.0.0.1', 53340)
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 284, in _handle_request_noblock
self.process_request(request, client_address)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 310, in process_request
self.finish_request(request, client_address)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 323, in finish_request
self.RequestHandlerClass(request, client_address, self)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/django/core/servers/basehttp.py", line 562, in __init__
BaseHTTPRequestHandler.__init__(self, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 641, in __init__
self.finish()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/SocketServer.py", line 694, in finish
self.wfile.flush()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py", line 301, in flush
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
----------------------------------------
[29/Jan/2011 09:20:27] "GET /users/2/ HTTP/1.1" 200 114593
SyntaxError::SyntaxError comes from the Python parser itself. I don't think this has anything to do with your form data.
I'd try running pylint, pyflakes or pep8 compliance on this code and see what it says.
I'm suspecting an error parsing one of your Python files, possibly some part of one of the files that's shown above, but not exactly what you have there. For example, a stray ( or [ or { character somewhere might cause this kind of problem, since the Form code isn't executed until called.
The odd indentation on your "required=True" parts of the ChefForm declaration support this guess. Your editor is indenting incorrectly because of some issue, likely above the entire declaration of "class ChefForm" that we can't see here.
EDIT: sorry I'm mistaken with my last reply. I was thinking of something else.
replace the %s with %d on this line:
return HttpResponseRedirect('/users/%s' % request.user.id)