Django - 添加自定义 class 到 label_tag

Django - Adding custom class to label_tag

我正在想办法在我的表单标签中添加 class。我想在没有像 crispyforms 这样的东西的情况下完成这个,如果可能的话不必编辑 html。根据我的知识和谷歌搜索,我花了几个小时试图解决这个问题,但我不能哈哈。我基本上只想在标签元素中输出一个 class ,如下所示:

<label class='text-muted' for="id_street_address">Street Address:</label>

我的模型如下:

class CheckoutForm(forms.Form):
    street_address = forms.CharField(widget=forms.TextInput(
        attrs={
            'class': 'form-control'
        }
    ))
    apartment = forms.CharField(required=False, widget=forms.TextInput(
        attrs={
            'class': 'form-control'
        }
    ))
    country = CountryField(blank_label='(select country)')
    zip_code = forms.CharField(widget=forms.TextInput(
        attrs={
            'class': 'form-control'
        }
    ))
    same_billing_address = forms.BooleanField(widget=forms.CheckboxInput())
    save_info = forms.BooleanField(widget=forms.CheckboxInput())
    payment_option = forms.BooleanField(widget=forms.RadioSelect())

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['street_address'].label = 'Street Address'
        self.fields['apartment'].label = 'Address 2 (optional)'
        self.fields['zip_code'].label = 'Zip Code'

我在模板中呈现我的表单是这样的:

<form>
              {% csrf_token %}
              {% for field in form %}
              <div class="form-group px-3 my-3">
              {{ field.label_tag }}
              {{ field }}
              {{ field.help_text }}
              {{ field.errors }}
              </div>
              {% endfor %}
            </form>

这可以吗?非常感谢任何帮助

实际呈现表单字段的 class 是 class BoundField。这个绑定字段有一个方法 label_tag [Django docs] ,你用它来呈现标签,这个方法接受一些可选参数,其中一个是 attrs 使用它我们应该能够添加 class你想要的属性。这里的问题是:

  1. 我们无法将参数传递给模板中的方法。
  2. 覆盖它也会涉及覆盖表单域,这意味着覆盖多个表单域。

一个解决方案是实现一个 custom template tag / filter 来为我们调用方法,这就是我将在这个答案中描述的内容。首先在你的一些合适的应用程序中创建一个目录 templatetags,向其中添加一个 __init__.py 文件,以及一个我们将在其中写入模板标签的文件(假设为 form_helpers.py)。因此,您的应用程序目录现在看起来像:

your_app/
    __init__.py
    models.py
    templatetags/
        __init__.py
        form_helpers.py
    views.py

接下来在form_helpers.py添加以下代码:

from django import template


register = template.Library()

@register.simple_tag
def render_label(bound_field, css_class):
    return bound_field.label_tag(attrs={'class': css_class})

接下来在你的模板中你可以写:

{% load form_helpers %}

<form>
    {% csrf_token %}
    {% for field in form %}
        <div class="form-group px-3 my-3">
            {% render_label field css_class="text-muted" %}
            {{ field }}
            {{ field.help_text }}
            {{ field.errors }}
        </div>
    {% endfor %}
</form>

注意:有一个名为 django-widget-tweaks 的用于手动呈现表单的很棒的包,如果您使用它,您可以简单地使用它的 add_required_class 过滤器。