2014-10-07 84 views
0

我試圖在http://django-crispy-forms.readthedocs.org/en/latest/crispy_tag_forms.htmlDjango的酥脆形式 - VariableDoesNotExist

做教程當我嘗試打開網頁,我得到下面的錯誤;

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 %} 
+0

該文檔不是一步一步教程 - 它只是記錄如何在'Django'中使用'crispy-forms'。首先通過[Django教程](https://docs.djangoproject.com/en/1.7/intro/tutorial01/)熟悉框架的不同部分如何在嘗試集成第三方之前相互交互應用程序如「脆皮形式」。在該教程之後,您可能還想查看[cookiecutter](https://github.com/audreyr/cookiecutter)及其關聯的[Django模板](https://github.com/pydanny/cookiecutter-django)以獲得最佳效果實踐。 – 2014-10-07 12:55:05

回答

1

您絕不會將表單實例傳遞給視圖的渲染器。

很簡單至少看到您的形式呈現......

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

你會想看看Django文檔,看看如何處理數據,從形式和返回等,但會讓你看它在頁面上呈現。

+0

確實是缺少的部分,謝謝 – phicon 2014-10-07 14:38:58