首页 > 解决方案 > 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文件中可能存在问题,但我已经查看了很多次,我没有发现任何问题。有什么想法吗?

标签: pythondjangodjango-formsdjango-views

解决方案


尝试

 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文件。

但似乎您可能正在尝试合并这两者,但在这种情况下,您需要一个视图,它既可以显示文件的内容,又可以请求文件。但是如果你有两个视图会更容易,让表单只接受输入,然后重定向到第二个视图以显示结果。


推荐阅读