如何解决ContactForm 未显示在页脚中
我正在尝试在 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})
联系人.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
感谢您的帮助!!
解决方法
您需要做一些事情才能使这项工作正常进行。
- 在使用该表单的每个页面的上下文中包含该表单(否则 DTL 怎么知道要呈现什么)。 例如:
def view_that_uses_base(request):
...
form = ContactForm
return render(request,'template_name.html',{'form':form})
- 另请注意,您需要为表单提供一个 action 属性。否则它将始终 POST 回您当前的 URL(它没有处理该帖子的逻辑),因此您需要将表单更改为:
<form method="post" action="{% url 'contact' %}">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。