【发布时间】:2021-03-30 18:47:40
【问题描述】:
我正在尝试在我的 base.html 的页脚中添加一个联系表单。尝试追踪我能找到的所有内容,但似乎无法找到为什么我的表单中的 3 个字段没有显示。这是我的代码:
forms.py
from django import forms
class ContactForm(forms.Form):
contact_name = forms.CharField(max_length = 50)
email_address = forms.EmailField(max_length = 150)
message = forms.CharField(widget = forms.Textarea)
views.py
from django.shortcuts import render, get_object_or_404, redirect
from .models import CoollegeProductModel, NonCoollegeProductModel
from .forms import ContactForm
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
subject = "Website Inquiry"
body = {
'contact_name': form.cleaned_data['contact_name'],
'email': form.cleaned_data['email_address'],
'message': form.cleaned_data['message'],
}
message = "\n".join(body.values())
try:
send_mail(subject, message, 'admin@example.com', ['admin@example.com'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('product/home.html')
form = ContactForm()
return render(request, "product/contact.html", {'form':form})
contact.html
<!--Contact form-->
<div style="margin:80px">
<h1>Contact</h1>
<h4>Contact us directly if you have any questions</h4>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</div>
base.html
<footer style="background-color: #e3f2fd">
{% include "product/contact.html" %}
</footer>
这是页脚显示的内容: enter image description here
感谢您的帮助!!
【问题讨论】:
-
您确定您的网址设置正确吗?您附上的图片来自
base.html,其中包括contact.html。但是你发布的视图是直接渲染contact.html。 -
嗨,蒂姆!在我的网址中,我有这个路径: path('contact', views.contact, name='contact') 如果我直接去 local/contact/ ,我可以看到联系表格工作得很好,但理想情况下我想要它显示在每页的页脚中。这就是我在页脚中写 include 语句的原因。有什么我做错了吗?谢谢!
-
如果您想在每个页面中包含表单,您需要确保每个页面的上下文中都包含表单实例。如果这没有发生,
{{ form.as_p }}没有任何意义。