【问题标题】:Why isn't my form rendering on the homepage为什么我的表单没有呈现在主页上
【发布时间】: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


【解决方案1】:

您的变量“form”只是在 if/else 中启动,因此在上下文中没有未定义。一种解决方案是使用 ContactForm() 作为默认值,如果它是一个发布请求,它将被覆盖。

def contactView(request): 
    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})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-27
    • 1970-01-01
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    相关资源
    最近更新 更多