gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:16:09 27 4
gpt4 key购买 nike

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

# 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com