Django crispy forms - VariableDoesNotExist

时间:2014-10-07 12:16:02

标签: python django twitter-bootstrap-3

我正在尝试在http://django-crispy-forms.readthedocs.org/en/latest/crispy_tag_forms.html

上完成教程

当我尝试打开页面时,我收到以下错误;

VariableDoesNotExist at / Failed lookup for key [example_form] in u

它试图查找example_form但找不到它。因为我对django和python真的很陌生,所以我很遗憾缺少这个部分。在这种情况下我还需要一个views.py,还是可以直接引用urls.py中的表单?

我的urls.py

    urlpatterns = patterns('',

        url(r'^$', 'ian.views.home', name='home'),
        url(r'^admin/', include(admin.site.urls)),
    )

我的views.py

def home(request):  
    return render_to_response("index.html",
                              context_instance=RequestContext(request))

我的forms.py

from crispy_forms.helper import FormHelper
from crispy_forms.layout import Submit

class ExampleForm(forms.Form):
    like_website = forms.TypedChoiceField(
        label = "Do you like this website?",
        choices = ((1, "Yes"), (0, "No")),
        coerce = lambda x: bool(int(x)),
        widget = forms.RadioSelect,
        initial = '1',
        required = True,
    )

    favorite_food = forms.CharField(
        label = "What is your favorite food?",
        max_length = 80,
        required = True,
    )

    def __init__(self, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_id = 'id-exampleForm'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'
        self.helper.form_action = 'submit_survey'

        self.helper.add_input(Submit('submit', 'Submit'))

我的index.html

{% load crispy_forms_tags %}
{% crispy example_form example_form.helper %}

1 个答案:

答案 0 :(得分:1)

您永远不会将表单实例传递给视图的渲染器。

非常简单地至少看到你的表格呈现......

def home(request):  
    example_form = ExampleForm()
    return render_to_response("index.html",
                              {"example_form": example_form},
                              context_instance=RequestContext(request))

您将需要查看django文档以了解如何处理从表单返回的数据等,但这样可以让您看到它在页面上呈现。