1

我不知道这里发生了什么:我以为我正在实现一个非常简单的 Django 表单,遵循 Django Docs 中的 ContactForm 示例(尽管我对 forms.py 使用了不同的示例)。但是,由于某种原因,当页面加载时,我得到了模板,但没有出现任何表单。根据模板,所有的 HTML 都在那里,但 Django 的东西(theTest我添加的表单和变量)没有呈现。

我有一半希望在我无法识别的地方出现并发症,但是,我担心我犯了一个 n00b 错误,我应该能够接受......

如果有人可以帮助我,我将不胜感激!

我的代码:

表格.py:

class ContactSupportForm(forms.Form):
    fields = ('theSubject', 'theMessage')
    widgets = {
        'theMessage': forms.Textarea(attrs={'cols': 55, 'rows': 12}),
        }
    error_css_class = 'error'
    required_css_class = 'required'

视图.py:

from forms import ContactSupportForm

@login_required
def postSupportMessage(theRequest):
"""The new view to which the support form is submitted"""
isLoggedIn = linfiniti.isUserLoggedIn(theRequest)
if isLoggedIn == True:
    myRequestingUser = theRequest.user
    myRequestingUserEmail = myRequestingUser.email
else:
    return HttpResponseForbidden()
if theRequest.POST:
    theForm = ContactSupportForm(theRequest.POST)
    if theForm.is_valid():
        theIssueSummary = theForm.cleaned_data['theSubject']
        theMessageDesc = theForm.cleaned_data['theMessage']
        theIssueDesc = '%s \n \n Username: %s \n \n User Email: %s' % \
            (theMessageDesc, myRequestingUser, myRequestingUserEmail)
        theIssue = json.dumps({
            "fields": {
                "project":
                      {
                      "key": "SUPPORT"
                      },
                "summary": theIssueSummary,
                "description": theIssueDesc,
                "issuetype": {
                     "name": "Bug"
                    }
                }
          })
        myRequest = urllib2.Request('http://MYURL')
        myAuthString = base64.standard_b64encode('%s:%s' % ('USERNAME', 'PASSWORD'))
        myRequest.add_header("Authorization", "Basic %s" % myAuthString)
        theResult = urllib2.urlopen(myRequest, theIssue, {'Content-Type': 'application/json'})
        myReturn = theResult.read()
        if myReturn:
            theNewKey = myReturn.key
            return HttpResponse(json.dumps({
                "success": True,
                "theNewKey": theNewKey
                }))
        else:
            return HttpResponse(json.dumps({
                "success": False
                }))
    else:
        theForm = ContactSupportForm()
        theTest = 'crap'
else:
    theForm = ContactSupportForm()
    theTest = 'rubbish'

return render_to_response('contact-support.html',
                                     {
                                     'theForm': theForm,
                                     'test': theTest
                                     },
                                     context_instance=RequestContext(theRequest)
                                     )

HTML:

<h5>Contact Support</h5>
      <div class="buttons" id="reload-support-form">
        <a data-ignore="true" class="btn btn-mini" href="javascript:void(null);" id="show-sent" onClick="reLoadSupportForm();">
          <i class="icon-refresh"></i> Reload Form
        </a>
      </div>
    </div>
    <h1>{{test}}</h1>
    <div class="widget-content" id="support-message-container">
      <div id="message-support-content">
        <form action="" method="post" id="compose-message-form" class="form-horizontal">

{% csrf_token %}
{% for field in theForm %}
  <fieldset class="control-group {% if field.errors %}error{% endif %}">
    <label class="control-label" for="{{ field.auto_id }}">{{ field.label }}</label>
    <div class="controls">
      {{ field }}
      {% if field.help_text %}
        <span class="help-inline">{{ field.help_text }}</span>
      {% endif %}
      {% if field.errors %}
        <span class="help-inline">{{ field.errors|striptags }}</span>
      {% endif %}
    </div>
  </fieldset>
{% endfor %}
<div class="control-group">
  <div class="controls">
    <input id="support-message-submit" class="btn btn-primary" type="submit"/>
  </div>
</div>

编辑

根据下面的答案/评论,我更新了 forms.py(我还else从视图中删除了第二个):

class ContactSupportForm(forms.Form):
theSubject = forms.CharField(max_length=100)
theMessage = forms.CharField(widget=forms.Textarea(attrs={'cols': 55, 'rows': 12}))
error_css_class = 'error'
required_css_class = 'required'

但是,我仍然没有在模板中获得表单,我也没有theTest在模板中获得。视图正确返回模板,但不返回表单或theTest.

4

1 回答 1

1

正如 Aamir 指出的那样,您没有在表单上定义任何字段,并且不清楚您从哪里得到按照您的方式进行操作的想法。文档清楚地显示了该怎么做:

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField(widget=forms.Textarea(attrs={'cols': 55, 'rows': 12}))
    error_css_class = 'error'
    required_css_class = 'required'

widgetsfields属性仅在 ModelForms 的内部 Meta 类中使用,它们是从模型生成的表单,当您想要覆盖该模型上的默认字段/字段小部件时。你在这里不这样做,所以他们没有意义。

此外,在您看来,您应该删除第二个else子句:当出现验证错误时,您将重新实例化表单,因此错误不会显示在 HTML 页面上。删除该子句将允许执行直接进入 render_to_response 调用。

(关于变量名的主题,除了驼峰式问题之外,我无法想象为什么你觉得需要在一半变量the前加上my.

于 2013-01-05T11:19:59.627 回答