【发布时间】:2020-07-01 16:15:29
【问题描述】:
尝试在此主页 div 上呈现我的表单:
<div class="col-5">
{% include "home/form.html" %}
</div>
这是我的 form.html:
<h1>Contact Us</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p}}
<div class="form-actions">
<button type="submit">Send</button>
</div>
</form>
views.py:
def home(request):
return render(request, "home/home.html")
def contactView(request):
if request.method == 'GET':
form = ContactForm()
else:
form = ContactForm(request.POST)
if form.is_valid():
subject = form.cleaned_data['subject']
from_email = form.cleaned_data['from_email']
message = form.cleaned_data['message']
try:
send_mail(subject, message, from_email, ['admin@example.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, "home/form.html",{'form':form})
def successView(request):
return HttpResponse('Success! Thank you for your message.')
当我将 contactView 和 home 合二为一并在 home.html 上呈现时效果很好。
谢谢
【问题讨论】:
-
您没有在
return render(request, 'home/home.html')中传递任何名为form的变量。有一些视图将form传递给home/form.html,这一事实并不重要。 -
但是由于我在 home.html 中包含了 form.html,所以它不应该在 home.html 中可见吗?那么您是否建议将所有内容放在一个视图中?
-
不,这只是意味着您还渲染了
form.html,但使用传递给根模板的相同变量。视图与模板无关,反之亦然。一个视图可以呈现零个、一个或多个模板(本身不是响应),一个模板可以包含在零个、一个或多个视图中。
标签: python django django-forms django-templates