django 的 form 如何进行添加样式

2017-03-24 19:26:31 +08:00
 fanne

我的 form.py 内容:

class LogSearchForm(forms.Form):
    platformId = forms.ChoiceField(label='所属平台',choices=platlist)
    gameOuterIp = forms.ChoiceField(label='游戏服',choices=gamelist)
    logid = forms.ChoiceField(label="日志类型",choices=logChoice)
    starttime = forms.DateTimeField(label="开始时间")
    endtime = forms.DateTimeField(label="结束时间")

里面有 forms.ChoiceField 字段,现在想在 html 里给这个字段添加样式要如何处理?

以下是我用 form 功能处理的一些方式

<form class="form-line" method="post" action="/items/search_log/">
{% csrf_token %}

<div class="form-group col-sm-1">
    <label>{{ log_form.platformId.label }}</label>
		{{ log_form.platformId}}
</div>
</form>		

如果不用 form 功能,自己写的话,如下信息:

<form class="form-inline" method="post" action="/items/search_log/">
 <div class="form-group col-sm-1">
   <label for="exampleInputName2">所属平台</label>
   <select id="id_select" class="form-control selectpicker" data-live-search="true" name="platformId">
       <option value="">平台</option>

       {% for plat in platlists %}
       <option value="{{ plat.plat_id }}">{{ plat.plat_name }}</option>
       {% endfor %}
   </select>
 </div>  
</form>

现在想用 form 功能,然后要带上样式

class="form-control selectpicker" data-live-search="true"

要怎么处理?

5908 次点击
所在节点    Django
5 条回复
marshalshi
2017-03-24 19:57:42 +08:00
daveze
2017-03-24 21:44:49 +08:00
class CommentForm(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={'class': 'special'}))
comment = forms.CharField(widget=forms.TextInput(attrs={'size': '40'}))
PythonAnswer
2017-03-24 22:01:41 +08:00
或者用 crispyform 然后重写 bootstrap 的 class
fanne
2017-03-25 07:16:50 +08:00
@marshalshi @daveze 这个我试过是可以的,但我不想在服务端中写,想在前端直接处理要怎么处理?
marshalshi
2017-03-25 16:30:15 +08:00
如果比较简单,可以自己写(比如文档里说的: https://docs.djangoproject.com/en/1.10/topics/forms/#rendering-fields-manually
或者 PythonAnswer 说的 crispyform ( http://django-crispy-forms.readthedocs.io/en/latest/)
或者也可以参考 crispyform ,写个 generic 的 templates + templatetags ( https://github.com/django-crispy-forms/django-crispy-forms/blob/dev/crispy_forms/templates/bootstrap/field.html)

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/350110

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX