我是Django表单,它可以检查表单是否有效:
if form.is_valid():
return HttpResponseRedirect('/thanks/')
Run Code Online (Sandbox Code Playgroud)
但是,如果它无效,我很想知道该怎么办?如何返回带有错误消息的表单?在任何一个例子中我都没有看到"其他".
我需要一些方法来为表单字段的label_tag()方法的输出添加一个类属性.
我看到有能力传入一个attrs字典,我已经在shell中测试了它,我可以做类似的事情:
for field in form:
print field.label_tag(attrs{'class':'Foo'})
Run Code Online (Sandbox Code Playgroud)
我会在输出中看到class ='Foo',但是我没有看到从模板中添加attrs参数的方法 - 实际上,模板是专门针对它设计的,不是吗?
我的表单定义中有一种方法来定义要在标签中显示的类吗?
在表单中,我可以执行以下操作为输入提供类
self.fields['some_field'].widget.attrs['class'] = 'Foo'
Run Code Online (Sandbox Code Playgroud)
我只需要输出它的类.
我决定今晚第一次尝试Bootstrap 3.我注意到,为了获得默认的,漂亮的表单字段样式,你需要为form-control
每个输入,textarea,select等添加一个类.这对那些动态生成表单的人来说很痛苦(例如,使用Django).Django允许您设置表单字段的属性,但要全局这样做需要一个令人讨厌的猴子补丁或非常非干的代码.
我正在使用django表单,我想在我的HTML中使用Twitter Bootstrap的css.所以我的模板看起来像这样:
{% for field in form %}
<div class="form-group">
{{ field.label_tag }}<!--Same thing as : <label for="{{field.id_for_label}}"></label> -->
<input type="{{field.type}}" class="form-control" id="{{field.auto_id}}" placeholder="Email">
</div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)
我无法弄清楚是否获得了类型值.{{field.type}}
.
有没有办法在django模板中获取输入字段的类型?
提前致谢
更新:
我问这个问题的原因是因为我希望能够将bootstrap类应用于input元素.但是在Bootstrap3中,要使用默认的css作为输入类型,你必须将form-control类添加到input元素,如下所示:<input type="text" class="form-control" id="{{field.auto_id}}" placeholder="">.
如果我使用django的字段,{{field}}
那么我无法添加表单控件类.我希望这能澄清一些事情.
我也看到了这个应用程序https://github.com/dyve/django-bootstrap3看起来像我想做的事情.令我惊讶的是,django不允许访问表单类型以允许更大的灵活性.
我正在使用Django CreateView,并且可以在模板中单独设置标签和字段。但是,我无法添加所需的引导程序类。目前,我有以下表格。
<form action="" method="post" class="form-horizontal">{% csrf_token %}
<div class="form-group">
<label class="control-label col-xs-1" for="name">{{ form.name.label }}:</label>
<div class="col-xs-9">
{{ form.name }}
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-1" for="name">{{ form.code.label }}:</label>
<div class="col-xs-9">
{{ form.code }}
</div>
</div>
<div class="form-group">
<label class="control-label col-xs-1" for="name">{{ form.phone.label }}:</label>
<div class="col-xs-9">
{{ form.phone }}
</div>
</div>
<input class="btn btn-primary col-xs-offset-1 col-xs-9" type="submit" value="Create" />
</form>
Run Code Online (Sandbox Code Playgroud)
如何在类变量名称,代码和电话中添加类?
我正在使用django-widget-tweaks并且无法弄清楚如何将字段变量添加为占位符,如下所示:
<div class="col-sm-10">
{{ field|append_attr:"class:form-control"|append_attr:"placeholder:field.label" }}
{% if field.help_text %}
<p class="help-block"><small>{{ field.help_text }}</small></p>
{% endif %}
</div>
Run Code Online (Sandbox Code Playgroud)
field.label
上面没有评估并将字符串"field.label"
作为页面上的占位符.
一些SO帖子建议注册一个自定义标签/过滤器,这似乎很简单.