V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
fanne
V2EX  ›  Django

django 的 form 如何进行添加样式

  •  
  •   fanne · 2017-03-24 19:26:31 +08:00 · 5894 次点击
    这是一个创建于 2583 天前的主题,其中的信息可能已经有所发展或是发生改变。

    我的 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"
    

    要怎么处理?

    5 条回复    2017-03-25 16:30:15 +08:00
    marshalshi
        1
    marshalshi  
       2017-03-24 19:57:42 +08:00 via iPhone
    daveze
        2
    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
        3
    PythonAnswer  
       2017-03-24 22:01:41 +08:00 via Android
    或者用 crispyform 然后重写 bootstrap 的 class
    fanne
        4
    fanne  
    OP
       2017-03-25 07:16:50 +08:00
    @marshalshi @daveze 这个我试过是可以的,但我不想在服务端中写,想在前端直接处理要怎么处理?
    marshalshi
        5
    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)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2701 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:54 · PVG 22:54 · LAX 07:54 · JFK 10:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.