9

对于 Django 上的酥脆形式,我不断得到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 %}

表格.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 %}

4

2 回答 2

11

模板标签的第一个参数是 Crispy Forms 期望实例crispy所在的上下文变量的名称。Form因此,您需要以某种方式Form在模板上下文中获取一个实例。如果您在视图中使用此表单,您可以执行类似的操作

def yourview(request):
    return TemplateResponse(request, "yourtemplate.html", {'form': LoginForm()})

如果您想在许多不同的页面上使用该表单,我建议使用包含标签

@register.inclusion_tag('path/to/login_form.html')
def display_login_form():
    return {'form': LoginForm()}

在您的模板中:

{% load your_template_tags %}
{% display_login_form %}

(另请参阅自定义模板标签的常规设置过程

于 2013-12-20T18:05:52.243 回答
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
于 2015-11-11T10:56:53.000 回答