嗨 Stackoverflow 人,
我无法使用基于类的视图呈现清晰的表单。当我使用基于函数的视图时,一切正常。
像往常一样,我生成 forms.py 如下:
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field
from item.models import Item
class CreateItemForm(forms.ModelForm):
class Meta:
model = Item
exclude = ('user',)
def __init__(self, *args, **kwargs):
self.helper = FormHelper()
self.helper.form_tag = False
self.helper.form_class = 'form-horizontal'
self.helper.layout = Layout(
Fieldset(
'Create your item here',
'name', 'description',
'save',
),
)
self.request = kwargs.pop('request', None)
return super(CreateItemForm, self).__init__(*args, **kwargs)
视图函数非常简单和标准:
from django.views.generic.edit import CreateView,
from item.models import Item
from item.forms import CreateItemForm
class ItemCreate(CreateView):
form_class = CreateItemForm
model = Item
template_name = 'item/item_create_form.html'
并且模板也遵循最少的说明:
{% extends "base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<h2>Create new Item</h2>
<form action="." class="crispy form-horizontal" method="post">
{% crispy form form.helper %}
</form>
{% endblock %}
我的问题是 Django 会抱怨“VariableDoesNotExist at /item/add/, Failed lookup for key [helper] in ...”。
酥脆的表单与基于类的视图兼容吗?我怎样才能交出帮助信息以正确创建表单?
感谢您的帮助和建议。