python - Django:网页上不可见的表单
问题描述
我正在尝试创建一个使用表单的简单 Django 网页,但我的表单不可见。我已阅读所有 Django 文档并阅读了与此问题相关的多个问题,但我没有找到解决我问题的解决方案。
以下是相关文件:
视图.py
from django.shortcuts import render
from .forms import FileForm
with open('calendar.txt') as f:
file_content = f.read()
def home(request):
return render(request, 'main/index.html',{'file_content':file_content})
def form_get(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = FileForm(request.POST)
# check whether it's valid:
if form.is_valid():
pass
else:
form = FileForm()
return render(request, 'index.html', {'form': FileForm.form})
网址.py
from django.conf.urls import url
from django.contrib import admin
from main import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.home, name='home'),
]
索引.py
{% extends "base.html" %}
{% block content %}
<h1>Welcome to the calendar!</h1>
<form action="/#" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
{{form}}
{% endblock content %}
根据我的阅读,我怀疑urls.py
文件中可能存在问题,但我已经查看了很多次,我没有发现任何问题。有什么想法吗?
解决方案
尝试
def form_get(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = FileForm(request.POST)
# check whether it's valid:
if form.is_valid():
pass
else:
form = FileForm()
return render(request, 'main/index.html', {'form': form})
看看我如何将渲染的上下文从 更改{'form': FileForm.form}
为{'form': form}
。index.html 文件的路径也是错误的。
修复视图后,您需要添加一个实际的 URL 以访问它。您当前的网址有
url(r'^$', views.index, name='home'),
请注意如何使用views.index
和不使用views.form_get
. 更改要使用的 URL,form_get
它将起作用。
url(r'^$', views.form_get, name='home'),
不知道您是否/
想去表格,或者您是否/
仍想回家,那里有表格的链接。但在这种情况下,您不想共享同一个index.html
文件。
但似乎您可能正在尝试合并这两者,但在这种情况下,您需要一个视图,它既可以显示文件的内容,又可以请求文件。但是如果你有两个视图会更容易,让表单只接受输入,然后重定向到第二个视图以显示结果。
推荐阅读
- yocto - Bitbake(例如 Yocto)在步骤中挂起:解析食谱
- c# - C# - 从 Azure AD 获取组信息
- c# - 所有方法均以 POSTMAN 形式工作,仅从 SPA 获取
- seo - 有没有办法将关键字列表添加到 Google 网站?
- jquery - Reactjs 中的 Jquery
- php - 无法在php中第二次在循环中执行程序
- c++ - 将 C 函数转换为 C++ 语言
- python - Django 显示的日期时间不会根据用户的本地时区而改变
- c# - 空格和正则表达式
- bash - bash脚本,如何检查条件是否为真,它应该检查下5次或下50秒相同的条件,它是真的,警报