python - 模板表单未在 Django 中呈现

标签 python django

我有一个想要显示的表单。
它看起来像这样:

# The template to be filled with the form:
# base.html
{% load staticfiles %}
<html>
    <head><title>{% block title %}{% endblock %}</title></head>
    <body>{% block content %}{% endblock %}</body>
</html>

具体模板

# home.html
{% extends 'base.html' %}

{% block title %}Main{% endblock %}

{% block content %}
  <h2>Home page</h2>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Login</button>
  </form>
{% endblock %}

View .py

def home(request):
    context = locals()
    template = 'home.html'
    return render(request, template, context)

url.py

from django.conf.urls import url
from .views import home as home_view

urlpatterns = [
    url(r'^home/$', home_view, name='home'),
]

这不会绘制{{ form.as_p }}。它只绘制提交按钮。
有什么想法吗?

最佳答案

您的问题源于这样一个事实:当您使用 {{ form }}{{ form.as_p }} 时,模板不知道您正在引用什么。模板在上下文中看不到与键 'form' 关联的值。

要解决此问题,请在 View 中创建一个 Form 对象,然后在调用 render 时将其包含在上下文中。确保上下文字典中与表单关联的键是'form'

关于python - 模板表单未在 Django 中呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48230149/

相关文章:

python - Django url confs 不匹配

python - 使用自定义验证器的 Django 文件验证无法按我的预期工作

python - 自日期(不是纪元!)至今的秒数

python - pandas 函数基于 dict 创建组合列

python - Django re_path 正则表达式不匹配

python - Django:按多对多关系的字段排序

python - 简单标记作为模板中的变量

python - 自定义 Django Crispy 表单中忽略了 ValidationError

django - 用是否存在匹配的相关对象来注释查询集

python - 试图将经度/纬度转换为笛卡尔坐标