python - 无法在 Django 中呈现表单

标签 python django django-forms

我正在尝试在 Django 中导入一个简单的单字段表单,并且我已经浏览了 YouTube 上描述相同内容的大量教程视频。然而,我无法在我的网络应用程序上呈现简单的表单。我很确定我正在做一些非常愚蠢的事情,但我仍然没有意识到。

我还将发布文件夹结构,以便您可以建议我是否在错误的views.py 文件中定义类/函数。

相应的源代码如下:

earthquake/views.py 文件

from django.shortcuts import render
from earthquake.forms import HomeForm
from django.views.generic import TemplateView

class HomeView(TemplateView):
    template_name = 'earthquake/home.html'

    def get(self, request, *args, **kwargs):
        form1 = HomeForm()
        argf = {
            'myform': form1
        }
        return render(request, self.template_name, argf)

forms.py

from django import forms

class HomeForm(forms.Form):
    post = forms.CharField()

home.html(片段)

<div class="container">
    <div class="jumbotron">
        <h1>Query Form</h1>
        <p>Please Enter the parameters you want to query against the USGS Earthquake DB</p>
        <div class="container">
        <form class="" method="post" action="">
            {% csrf_token %}
            {{ myform }}
            <button type="submit" class="btn btn-success">Search</button>
        </form>
        </div>
    </div>
</div>

Django 项目 URL (interview.py/urls.py)

from django.contrib import admin
from django.urls import path, include
from interview.views import login_redirect
from interview import views
from django.contrib.auth.views import LoginView
from django.contrib.auth.views import LogoutView

urlpatterns = [
    path('', login_redirect, name='login_redirect'),
    path('admin/', admin.site.urls),
    path('home/', include('earthquake.urls')),
    path('login/', LoginView.as_view(template_name='earthquake/login.html'), name="login"),
    path('logout/', LogoutView.as_view(template_name='earthquake/logout.html'), name="logout"),
    path('register/', views.register, name='register'),
]

应用程序 URL (interview/earthquake/urls.py)

from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.home, name='home'),
]

文件夹结构

/image/zoehT.jpg

(如果您无法看到图像中的最后一个条目,它是项目文件夹中存在的主要views.py)。

以下是我当前获得的渲染快照:

/image/kXR7W.jpg

最佳答案

我看到在您的主视图文件中,您的基于类的 View 被称为

HomeView(TemplateView)

然而,在您的应用程序网址中,您将 View 包含为 view.home ,而它应该是 view.HomeView

除此之外,这是一个基于分类的 View ,因此您的 url 页面应如下所示:

from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.home.as_view(), name='home'),
]

因为这是一个基于类的 View 。

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

相关文章:

python - 使用 selenium python webdriver 滚动网页

python - “AutoField”对象没有属性 'remote_field'

python - 从查找表返回索引,允许空值且未找到

Python Beautiful Soup find_all

python - Django 测试 TemplateDoesNotExist

mysql - 警告 : ? : (mysql. W002)

python - 从提交在 Django 中运行 Python 脚本

django - 需要帮助设置 django-filetransfers

python - django 使用 ModelMultipleChoiceField 和 CheckboxSelectMultiple() 小部件以表单呈现初始值

python - 我的程序无法使用 Python 中的 mysql 连接器库在 MySQL 中存储值