如何使用基于 class 的视图呈现表单?

How to render form with class-based view?

我有一个索引页:

views.py

class IndexView(TemplateView):
    template_name = "index.html"

urls.py

urlpatterns = [
    path('', IndexView.as_view()),
]

我需要在这个页面渲染表单

index.html

{% block content %}
    <!-- Other blocks -->
    <div id="input">
        <form method="POST" class="text-form">
            {% csrf_token %}
            {{ form.as_p }}
            <button type="submit" class="submit btn">Submit</button>
        </form>
    </div>
    <!-- Other blocks -->
{% endblock %}

forms.py

class TextForm(forms.Form):
    text = forms.CharField(widget=forms.Textarea)

a topic about class-based views forms handling 但我不清楚如何用这种形式呈现 HTML

现在您没有将表单传递给上下文。你可以利用FormView [Django-doc] or other views that use a form like a CreateView [Django-doc], UpdateView [Django-doc]

因此您可以定义一个 FormView 并将 form_class attribute [Django-doc] 设置为您希望渲染的 class:

# app/views.py

from app.forms import <b>TextForm</b>
from django.views.generic.edit import <b>FormView</b>

class IndexView(<b>FormView</b>):
    template_name = 'index.html'
    <b>form_class = TextForm</b>

@PavelAntspovich:如果它生成post,它会自动构建表单并将request.POSTrequest.FILES传递给它,并检查它是否有效。如果是,它将调用 form_valid method [Django-doc] with the form as parameter. If not, it will call the form_invalid method [Django-doc]。这些方法需要return一个HttpResponse(也就是再查看结果)。