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)
Related
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.
I encountered the following in my Django files when I attempt to use the class based view CreateView.
AttributeError at /overview/new/
type object 'Project' has no attribute '_meta'
I have no idea why the _meta attribute is not there. I inherited my model from models.Model as usual, but I can't find any questions that have the same problem. I posted my files down below, can somebody help me fix this problem?
views.py:
from django.shortcuts import render, redirect
from django.contrib.auth import logout, authenticate, login
from django.contrib import messages
from django.views.generic import ListView, DetailView, CreateView
from projects.models import Project, Task
class CreateProject(CreateView):
model = Project
fields = ['title', 'description']
def form_valid(self, form):
form.instance.author = self.request.user
return super().form_valid(form)
models.py:
from django.db import models
from django.contrib.auth.models import User
from .CustomIDConstructor import ID
class Project(models.Model):
title = models.CharField(max_length=100, default='No title')
description = models.TextField(default='No description')
author = models.ForeignKey(User, on_delete=models.CASCADE)
customid = models.CharField(max_length=30, default=ID, editable=False, primary_key=True)
def __str__(self):
return self.title
urls.py:
from django.urls import path
from . import views
from projects.views import ProjectsOverview, Project, CreateProject
from django.contrib.auth.decorators import login_required
urlpatterns = [
path('', login_required(views.ProjectsOverview.as_view()), name='projects-projectsoverview'),
path('project/<pk>/', login_required(views.Project.as_view()), name='projects-project'),
path('new/', login_required(views.CreateProject.as_view()), name='projects-newproject')
]
Project_form.html:
{% extends "home/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container mt-4">
<form method="POST">
{% csrf_token %}
{{ form|crispy }}
<button style="background-color:rgb(130, 130, 130); color:white; border: none" class="btn btn-outline-info" type="submit">Create new project</button>
</form>
</div>
{% endblock content %}
Full traceback:
Internal Server Error: /overview/new/
Traceback (most recent call last):
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\edit.py", line 168, in get
return super().get(request, *args, **kwargs)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\edit.py", line 133, in get
return self.render_to_response(self.get_context_data())
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\edit.py", line 66, in get_context_data
kwargs['form'] = self.get_form()
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\edit.py", line 32, in get_form
form_class = self.get_form_class()
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\views\generic\edit.py", line 101, in get_form_class
return model_forms.modelform_factory(model, fields=self.fields)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\models.py", line 551, in modelform_factory
return type(form)(class_name, (form,), form_class_attrs)
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\models.py", line 256, in __new__
apply_limit_choices_to=False,
File "C:\Users\Gebruiker\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\forms\models.py", line 139, in fields_for_model
opts = model._meta
AttributeError: type object 'Project' has no attribute '_meta'
[05/Mar/2019 14:00:15] "GET /overview/new/ HTTP/1.1" 500 115370
From your URLs, it looks like you have a view Project which is clashing with the model Project.
path('project/<pk>/', login_required(views.Project.as_view()), name='projects-project'),
The simplest fix would be to rename that view, for example to ProjectDetail, and update the URL pattern.
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've done a lot of research trying to solve this problem myself but I am running up short of a solution. If anyone can give me any pointer or help I would really appreciate it.
I am creating a blog that has basic blog functionality such as; likes, dislikes, posts, comments, multiple users, CRUD functions etc. I have so far been able to overcome most of my problems and I am near the completion of this project.
The last bit of trouble I am having is with my Edit Comment functionality, I can delete a comment just fine but if I try to update a comment I got the following error:
ERROR 2017-03-08 14:26:21,907 wsgi.py:279]
Traceback (most recent call last):
File "/home/crow/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/runtime/wsgi.py", line 267, in Handle
result = handler(dict(self._environ), self._StartResponse)
File "/home/crow/Downloads/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.3/webapp2.py", line 1519, in __call__
response = self._internal_error(e)
File "/home/crow/Downloads/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.3/webapp2.py", line 1511, in __call__
rv = self.handle_exception(request, response, e)
File "/home/crow/Downloads/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.3/webapp2.py", line 1505, in __call__
rv = self.router.dispatch(request, response)
File "/home/crow/Downloads/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.3/webapp2.py", line 1253, in default_dispatcher
return route.handler_adapter(request, response)
File "/home/crow/Downloads/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.3/webapp2.py", line 1077, in __call__
return handler.dispatch()
File "/home/crow/Downloads/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.3/webapp2.py", line 547, in dispatch
return self.handle_exception(e, self.app.debug)
File "/home/crow/Downloads/google-cloud-sdk/platform/google_appengine/lib/webapp2-2.3/webapp2.py", line 545, in dispatch
return method(*args, **kwargs)
File "/home/crow/UdacityProjects/blog/blog.py", line 424, in post
comment.text = self.request.get('comment_text')
File "/home/crow/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/ext/db/__init__.py", line 617, in __set__
value = self.validate(value)
File "/home/crow/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/ext/db/__init__.py", line 2810, in validate
value = super(UnindexedProperty, self).validate(value)
File "/home/crow/Downloads/google-cloud-sdk/platform/google_appengine/google/appengine/ext/db/__init__.py", line 644, in validate
raise BadValueError('Property %s is required' % self.name)
BadValueError: Property text is required
Now I am not exactly sure why this is happening, I looked up the solutions that others were finding for similar problems and none seemed to apply to my situation. Here is my relevant code for reference:
EditComment(BlogHandler)
class EditComment(BlogHandler):
def get(self, post_id, comment_id):
post = Post.get_by_id(int(post_id), parent=blog_key())
comment = Comment.get_by_id(int(comment_id))
if comment:
if comment.user.name == self.user.name:
self.render("editcomment.html", comment_text=comment.text)
else:
error = "You may only edit your own comments"
self.render("editcomment.html", edit_error=error)
else:
error = "This comment no longer exists"
self.render("editcomment.html", edit_error=error)
def post(self, post_id, comment_id):
if self.request.get("update_comment"):
comment = Comment.get_by_id(int(comment_id))
if comment.user.name == self.user.name:
comment.text = self.request.get('comment_text')
comment.put()
time.sleep(0.1)
self.redirect('/post/%s' % str(post_id))
else:
error = "you may only edit your own comments"
self.render(
"editcomment.html",
comment_text=comment.text,
edit_error=error)
elif self.request.get("cancel"):
self.redirect('/post/%s' % str(post_id))
Comment(db.model)
class Comment(db.Model):
user = db.ReferenceProperty(User, required=True)
post = db.ReferenceProperty(Post, required=True)
created = db.DateTimeProperty(auto_now_add=True)
text = db.TextProperty(required=True)
#classmethod
def cdb_blog_id(cls, blog_id):
c = Comment.all().filter('post =', blog_id)
return c.count()
#classmethod
def adb_blog_id(cls, blog_id):
c = Comment.all().filter('post =', blog_id).order('created')
return c
editcomment.html
{% extends "base.html" %}
{% block content %}
<div class="twelve columns">
<h3>Edit Comment</h3>
<hr>
<div class="row">
<div class="twelve columns">
<form method="post">
<label>
<textarea class="u-full-width" name="text" id="texta2">{{comment_text}}</textarea>
</label>
<div class="error">{{edit_error}}</div>
<input type="submit" class="button" name="update_comment" value="Update">
<input type="submit" class="button" name="cancel" value="Cancel">
</form>
</div>
</div>
</div>
{% endblock %}
Now the traceback does not point to the area in my code that is causing the issue so I will provide the relevant lines of the __inti__.py file here:
Line 617
def __set__(self, model_instance, value):
"""Sets the value for this property on the given model instance.
See http://docs.python.org/ref/descriptors.html for a description of
the arguments to this class and what they mean.
"""
value = self.validate(value)
setattr(model_instance, self._attr_name(), value)
Line 2810
raise BadValueError('Property %s must be convertible '
'to a %s instance (%s)' %
(self.name, self.data_type.__name__, err))
value = super(UnindexedProperty, self).validate(value)
if value is not None and not isinstance(value, self.data_type):
raise BadValueError('Property %s must be a %s instance' %
(self.name, self.data_type.__name__))
return value
Line 644
if self.empty(value):
if self.required:
raise BadValueError('Property %s is required' % self.name)
I'm not sure what I'm doing wrong here, and if anyone would be able to offer me any kind of advice I would be very grateful. Thanks again
The error indicates that the value you get from self.request.get('comment_text') and pass to comment.text is invalid - None probably.
The check is done because the text property has the option required set to True in the Comment model.
So check that you properly pass the 'comment_text' request parameter (or its value) around.
Maybe you need name="comment_text" in the following line from editcomment.html?
<textarea class="u-full-width" name="text" id="texta2">{{comment_text}}</textarea>
Sorry if its a noob code or question. I am doing pagination using django-pagination and I am doing it like this.But this gives me keyError at on my page furthermore it mentions that its an error during template rendering. What I am doing wrong here.I have successfully installed pagination, modified the settings.py file. But i dont know what i need to do here. Any help would be highly appreciated.
<table class="active_table" summary="active_user">
<thead>
<tr><th>Name</th><th>Mobile Number</th><th>Count</th></tr>
</thead>
<tbody id="table_content">
{% load pagination_tags %}
{% block content %}
{% autopaginate response_data 5 %}
{% for b in response_data %}
<tr class="table_rows"><td>{{ b.name }}</td><td>{{ b.mobile_number }}</td><td>{{ b.count }}</td></tr>
{% endfor %}
{% paginate %}
{% endblock %}
</tbody>
</table>
The detailed traceback is pasted here http://dpaste.com/919526/
The viewcode is following
views.py
#csrf_exempt
def active_user_table(request, b):
if request.method != "GET":
raise Http404
if (b=='4'):
cursor = connection.cursor()
cursor.execute("SELECT core_user.id, name,mobile_number,COUNT(*) as count, created FROM core_user,core_useractivity WHERE core_user.id = core_useractivity.user_id GROUP BY user_id ORDER BY count DESC")
response_data = dictfetchall(cursor)
return render_to_response("siteadmin/active_user_table.tmpl",{'response_data':response_data})
elif (b=='3'):
cursor = connection.cursor()
cursor.execute("SELECT core_user.id, name, mobile_number, COUNT(*) as count, created FROM core_user, core_useractivity WHERE core_user.id = core_useractivity.user_id AND MONTH(CAST(created as date)) = MONTH(NOW()) AND YEAR(cast(created as date)) = YEAR(NOW()) GROUP BY user_id ORDER BY count DESC")
response_data = dictfetchall(cursor)
return render_to_response("siteadmin/active_user_table.tmpl",{'response_data': response_data})
elif (b=='2'):
cursor = connection.cursor()
cursor.execute("SELECT core_user.id, name, mobile_number, COUNT(*) as count, created FROM core_user, core_useractivity WHERE core_user.id = core_useractivity.user_id AND DATEDIFF(NOW(), created) <= 7 GROUP BY user_id ORDER BY count DESC")
response_data = dictfetchall(cursor)
return render_to_response("siteadmin/active_user_table.tmpl",{'response_data': response_data})
elif (b=='1'):
cursor = connection.cursor()
cursor.execute("SELECT core_user.id, name, mobile_number, COUNT(*) as count, created FROM core_user, core_useractivity WHERE core_user.id = core_useractivity.user_id AND DATE(created) = DATE(NOW())")
response_data = dictfetchall(cursor)
return render_to_response("siteadmin/active_user_table.tmpl",{'response_data': response_data})
else:
raise Http404
Sorry I am not using django ORM as of now but I will do so in future.
You must add context_instance in render_to_response call:
return render_to_response("siteadmin/active_user_table.tmpl",{'response_data': response_data}, context_instance=RequestContext(request))
or you can use TEMPLATE_CONTEXT_PROCESSORS tuple in your settings.py. Add this string "django.core.context_processors.request" to context processors and every RequestContext will contain a variable request.
I solved it myself but thanks to ndpu for helping me atleast I got confident there were no other issue but some settings issue. In this question I have problems with setting up django-pagination. Alasdair had mentioned adding "django.contrib.auth.context_processors.auth", to TEMPLATE_CONTEXT_PROCESSORS . On just adding it I am getting the correct expected values.
For those who are using the render shortcut
and still facing this error, just add {'request': request } to the context variable
context = { ..., 'request':request}
return render(request, 'templatename.html', context)
I also face this error earlier. I was getting following error:
Internal Server Error: /cancel-email/
Internal Server Error: /cancel-email/
Traceback (most recent call last):
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/base.py", line 506, in parse
compile_func = self.tags[command]
KeyError: 'static'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view
return view_func(*args, **kwargs)
File "/var/www/recruiter-new/recruiter/scheduler.py", line 803, in cancelEmail
return render(request,'scheduler/cancel-email-part.html',{"cancel_email" :EmailDetail})
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/shortcuts.py", line 67, in render
template_name, context, request=request, using=using)
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/loader.py", line 96, in render_to_string
template = get_template(template_name, using=using)
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/loader.py", line 32, in get_template
return engine.get_template(template_name, dirs)
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/backends/django.py", line 40, in get_template
return Template(self.engine.get_template(template_name, dirs), self)
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/engine.py", line 190, in get_template
template, origin = self.find_template(template_name, dirs)
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/engine.py", line 157, in find_template
name, template_dirs=dirs, skip=skip,
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/loaders/base.py", line 46, in get_template
contents, origin, origin.template_name, self.engine,
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/base.py", line 189, in __init__
self.nodelist = self.compile_nodelist()
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/base.py", line 230, in compile_nodelist
return parser.parse()
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/base.py", line 508, in parse
self.invalid_block_tag(token, command, parse_until)
File "/home/kashif/recEnv/lib/python3.6/site-packages/django/template/base.py", line 568, in invalid_block_tag
"or load this tag?" % (token.lineno, command)
django.template.exceptions.TemplateSyntaxError: Invalid block tag on line 74: 'static'. Did you forget to register or load this tag?
[07/Aug/2018 08:43:26] "POST /cancel-email/ HTTP/1.1" 500 20789
I tried some google solutions but couldn't resolved, then finally again check my code and found a silly mistake on template file.
Just add:
{% load static %}
on top of your template file.