简体   繁体   English

将 CSS 添加到 django 模板中的表单字段

[英]Add CSS to form field in django template

I want to use bootstrap on django form.我想在 django 表单上使用引导程序。 To do so I need to add .form-control class to each field.为此,我需要向每个字段添加.form-control类。 My workaround is:我的解决方法是:

def __init__(self, *args, **kwargs):
    super(SomeForm, self).__init__(*args, **kwargs)
    for field in self.fields:
        self.fields[field].widget.attrs = {
            'class': 'form-control'
        }
{% for field in form %}
    <div class="form-group">
        {{ field.label_tag }}
        {{ field }}
    </div>
{% endfor %}

But I believe it's wrong to put CSS in python code (if I would want to use another CSS framework, I would have to change form class).但我认为将 CSS 放在 python 代码中是错误的(如果我想使用另一个 CSS 框架,我将不得不更改表单类)。 How can I move the class to template?如何将类移动到模板? I would not like to use crispy not to be bound to bootstrap.我不想使用脆皮而不是引导程序。

You can use a custom template tag for adding a class, see more information here您可以使用自定义模板标签来添加类,请在此处查看更多信息

You will have to create a new module inside the templatetags directory:您必须在 templatetags 目录中创建一个新模块:

myapp/
    __init__.py
    models.py
    templatetags/
        __init__.py
        extra_filters.py <-- Name it as you prefer
    views.py
    forms.py

The content of your extra_filters.py module can be something like this: extra_filters.py 模块的内容可以是这样的:

from django import template

register = template.Library()


@register.filter(name='addclass')
def addclass(field, myclass):
    return field.as_widget(attrs={"class": myclass})

Now in your template, load the new filter and use it as follows:现在在您的模板中,加载新过滤器并按如下方式使用它:

{% load extra_filters %}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM