سؤال

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)
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top