【问题标题】:ContactForm not showing up in footer联系表格未显示在页脚中
【发布时间】: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 }} 没有任何意义。

标签: html django forms footer


【解决方案1】:

您需要做一些事情才能使其正常工作。

  1. 在使用该表单的每个页面的上下文中包含该表单(否则 DTL 将如何知道要呈现的内容)。 例如:
def view_that_uses_base(request):
    ...
    form = ContactForm
    return render(request, 'template_name.html', {'form':form})
  1. 另请注意,您需要为表单提供操作属性。否则,它总是会 POST 回您当前的 URL(它没有处理该帖子的逻辑),因此您需要将表单更改为:
  <form method="post" action="{% url 'contact' %}">
    {% csrf_token %}
      {{ form.as_p }}
      <button type="submit">Submit</button>
  </form>

【讨论】:

  • 有没有办法让我只在 base.html 中有表单,这样我就不必进行那么多渲染了?我们的想法是在每个页面的页脚中都有联系表单,例如导航栏。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-24
  • 1970-01-01
  • 2015-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多