对于Django上的crispy表单,我不断收到VariableDoesNotExist at /
Failed lookup for key [form] in u'[{\'False\': False, \'None\': None,.....
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block loginForm %}
<div class="container" style="padding-bottom: 70px;">
<div class='row'>
<div class='col-md-6 col-md-offset-3'>
<div class="well">
<legend>Sign in</legend>
<form method="post" action="{% url 'django.contrib.auth.views.login' %}" class="form-horizontal">
{% crispy form %}
<input type="hidden" name="next" value="{{ next }}"/>
</form>
</div>
</div>
</div>
</div>
{% endblock loginForm %}
forms.py:
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Div, Submit, HTML, Button, Row, Field, Hidden, Fieldset
from crispy_forms.bootstrap import AppendedText, PrependedText, FormActions
from django.contrib.auth.forms import AuthenticationForm
class LoginForm(AuthenticationForm):
def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
self.helper = FormHelper()
self.helper.form_class = 'form-horizontal'
self.helper.label_class = 'col-lg-2'
self.helper.field_class = 'col-lg-8'
self.helper.form_tag = False
self.helper.layout = Layout(
Field('username', placeholder="username", css_class='input-xlarge'),
Field('password', placeholder="Password", css_class='input-xlarge'),
FormActions(
Submit('login', 'Login', css_class="btn-primary"),
)
)
我不明白,因为根据文档我在属性帮助器上使用FormHelper所以我应该能够使用{%crispy form%}
答案 0 :(得分:9)
crispy
模板标记的第一个参数是Crispy Forms期望Form
实例的上下文变量的名称。因此,您需要以某种方式在模板上下文中获取Form
实例。如果您在视图中使用此表单,则可以执行类似
def yourview(request):
return TemplateResponse(request, "yourtemplate.html", {'form': LoginForm()})
如果您想在多个不同的网页上使用该表单,我建议使用inclusion tag:
@register.inclusion_tag('path/to/login_form.html')
def display_login_form():
return {'form': LoginForm()}
在你的模板中:
{% load your_template_tags %}
{% display_login_form %}
答案 1 :(得分:2)
我遇到了VariableDoesNotExist
问题以及Failed lookup for key [form]
,但对我来说问题是我错误地使用generic.DetailView
作为基类而不是generic.UpdateView
。
更改为UpdateView
解决了问题。
class MyUpdateView(generic.UpdateView):
template_name = "object_update.html"
model = MyModel
form_class = MyCreateForm