Django:语法错误“意外的 EOF”保存表单时
我有一个设置页面,其中有两种表单用于处理两个不同模型的设置。 Profile 模型表单有效。 Chef 模型则没有。表单正常失败,并且不会抛出 Django 错误页面 - 因此在使用 pdb 时,我发现表单无效,并且抛出语法错误。
我很困惑这个错误来自哪个字段。任何帮助将不胜感激。谢谢!
错误:
*** 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!'}
查看:
@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))
要向此错误添加更多信息,我能够提取此信息管道破裂错误:
[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
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
SyntaxError::SyntaxError 来自 Python 解析器本身。我认为这与您的表单数据没有任何关系。
我会尝试运行 pylint,pyflakes 或此代码的 pep8 合规性看看它说什么。
我怀疑解析您的 Python 文件之一时出现错误,可能是上面显示的文件之一的某些部分,但不完全是您那里的内容。例如,某个地方的杂散 ( 或 [ 或 { 字符可能会导致此类问题,因为表单代码在调用之前不会执行。ChefForm
声明的“required=True”部分上的奇怪缩进支持这种猜测。您的由于某些问题,编辑器缩进不正确,可能在我们在这里看不到的“class ChefForm”的整个声明之上。
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.
编辑:抱歉我上次的回复弄错了。我在想别的事情。
将这一行中的 %s 替换为 %d:
EDIT: sorry I'm mistaken with my last reply. I was thinking of something else.
replace the %s with %d on this line: