1

我从不久前开始研究 Django 表单。我一直让表单由他们自己生成,只需编写:

{{ test_form.as_p  }}

成功了。

然后我决定解决这个问题来定制这个模板,但由于某种原因,这条线:

{{ form.subject }}

不显示表格。我误解了文档吗?我还检查了生成的 HTML,它有点简单地跳过了 {{ form.suject }}

这是代码:

模板:

<form action="/contact/" method="post">
{{ form.non_field_errors }}
<div class="fieldWrapper">
    {{ form.subject.errors }}
    <label for="id_subject">Email subject:</label>
    {{ form.subject }}
</div>
<div class="fieldWrapper">
    {{ form.message.errors }}
    <label for="id_message">Your message:</label>
    {{ form.message }}
</div>
<div class="fieldWrapper">
    {{ form.sender.errors }}
    <label for="id_sender">Your email address:</label>
    {{ form.sender }}
</div>
<p><input type="submit" value="Send message" /></p>

和相关的视图:

def contact(request):

if request.method == 'POST':
    form = contact_form(data=request.POST)
    if form.is_valid():
        subject = form.cleaned_data['subject']
        message = form.cleaned_data['message']
        sender = form.cleaned_data['sender']
        recipents = ['grit.erlum@gmail.com']
        send_mail(subject, message, sender, recipents)
        print 'mail sent'
return render_to_response('contact.html', {'contact_form' : contact_form}, context_instance=RequestContext(request))

当然还有表单类:

class contact_form(forms.Form):

subject = forms.CharField(max_length=100)
message = forms.CharField(max_length=1000, widget=forms.Textarea)
sender = forms.EmailField()
4

2 回答 2

1

在您的 render_to_response 中,只需更改:

{'contact_form':contact_form}

{'form':contact_form}

或您的模板,将 {{ form.xxx }} 更改为 {{ contact_form.xxx }}

于 2012-07-18T15:13:08.983 回答
0

您的视图没有contact_form定义变量,但您将其传递给render_to_response. 您还需要创建表单的未绑定版本并将其传递给render_to_response喜欢:

def contact(request):
    if request.method == 'POST':
        form = contact_form(data=request.POST)
        if form.is_valid():
            ...
    else:
        form = contact_form() # An unbound form
        return render_to_response('contact.html', {'form' : form}, context_instance=RequestContext(request))
于 2012-07-18T16:16:27.297 回答