Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 向django模板中的表单字段添加CSS_Python_Html_Css_Django_Twitter Bootstrap - Fatal编程技术网

Python 向django模板中的表单字段添加CSS

Python 向django模板中的表单字段添加CSS,python,html,css,django,twitter-bootstrap,Python,Html,Css,Django,Twitter Bootstrap,我想在django表单上使用引导。为此,我需要向每个字段添加.formcontrol类。我的解决办法是: def\uuuu init\uuuu(self,*args,**kwargs): 超级(某种形式,自我)。\uuuuu初始值(*args,**kwargs) 对于self.fields中的字段: self.fields[field].widget.attrs={ “类”:“窗体控件” } {%用于表单%]中的字段 {{field.label_tag} {{field}} {%endfor%

我想在django表单上使用引导。为此,我需要向每个字段添加
.formcontrol
类。我的解决办法是:

def\uuuu init\uuuu(self,*args,**kwargs):
超级(某种形式,自我)。\uuuuu初始值(*args,**kwargs)
对于self.fields中的字段:
self.fields[field].widget.attrs={
“类”:“窗体控件”
}
{%用于表单%]中的字段
{{field.label_tag}
{{field}}
{%endfor%}

但我认为将CSS放在python代码中是错误的(如果我想使用另一个CSS框架,我必须更改表单类)。如何将类移动到模板?我不想使用crispy来不绑定到引导程序。

您可以使用自定义模板标记来添加类,请参阅更多信息

您必须在templatetags目录中创建一个新模块:

myapp/
    __init__.py
    models.py
    templatetags/
        __init__.py
        extra_filters.py <-- Name it as you prefer
    views.py
    forms.py
现在在模板中,加载新过滤器并按如下方式使用:

{% load extra_filters %}

{% for field in form %}
    <div class="form-group">
        {{ field.label_tag }}
        {{ field|addclass:"form-control" }}
    </div>
{% endfor %}
{%load extra_filters%}
{%形式的字段为%}
{{field.label_tag}
{{field | addclass:“表单控件”}
{%endfor%}
{% load extra_filters %}

{% for field in form %}
    <div class="form-group">
        {{ field.label_tag }}
        {{ field|addclass:"form-control" }}
    </div>
{% endfor %}