如何在django表单声明中设置一个标签的css类? [英] How to set css class of a label in a django form declaration?

查看:169
本文介绍了如何在django表单声明中设置一个标签的css类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用django-uniform并使用一些统一的功能,我正在寻找一种直接从form声明添加css类的方法(对于独立小部件)。

I'm using django-uniform and to use some uniform features, I'm looking for a way to add css class directly from form declaration (for independents widgets).

(作为一个奖励,这里是我可重用的只读自制的mixin片段...)

(as a bonus, here my reusable read-only home made mixin snippet...)

from django import forms

def _get_cleaner(form, field):
    def clean_field():
        return getattr(form.instance, field, None)
    return clean_field

class UniformROMixin(forms.BaseForm):
    """
    UniformROMixin, inherits to turn some fields read only

      - read_only = list of field names.
    """

    def __init__(self, *args, **kwargs):
        super(UniformROMixin, self).__init__(*args, **kwargs)
        if hasattr(self, "read_only"):
            if self.instance and self.instance.pk:
                for field in self.read_only:
                    self.fields[field].widget.attrs['readonly'] = True
                    self.fields[field].widget.attrs['class'] += "readOnly"
                    # here I would like to set css class of the label
                    # created from the self.fields[field].label string
                    setattr(self, "clean_" + field, _get_cleaner(self, field))



My only way for now is to add a bit of javascript on my generic form template and add classes manualy.

任何精彩的想法?

推荐答案

我发现这个片段可能是一个很好的答案:

I found this snippet which may be a good answer:

如何将css类和*添加到必填字段的标签

这里适应我的需要(尚未测试,我会编辑完成后):

here an adaptation to my needs (not tested yet, I'll edit the post once done):

from django.utils.html import escape

def readonly_cssclass_adder(bound_field, label_content, label_attrs):
    if 'readonly' in bound_field.field.widget.attrs:
        if 'class' in attrs:
            label_attrs['class'] += " readOnly"
        else:
            label_attrs['class'] = "readOnly"
    return label_content, label_attrs


def add_required_label_tag(original_function, tweak_foos=None):
    if not tweak_foos:
        return original_function

    def required_label_tag(self, contents=None, attrs=None):
        contents = contents or escape(self.label)
        if attrs is None:
            attrs = {}
        for foo in tweak_foos:
            contents, attrs = foo(self, contents, attrs)
        return original_function(self, contents, attrs)
    return required_label_tag

def decorate_bound_field():
    from django.forms.forms import BoundField
    BoundField.label_tag = add_required_label_tag(BoundField.label_tag, 
                                           tweak_foos=[readonly_cssclass_adder])

如果你有一个更好的解决方案,不调整所有的BoundField类我还在听。

If you have a better solution which don't tweak all the BoundField class I'm still listening.

编辑:
可能链接到django统一的方式来处理所需的字段,但似乎不调用 readonly_cssclass_adder 。但是我发现另一个更容易的解决方案,我的readOnly小部件自动转为readOnly ctrlHolder

edit: may be linked to django uniform way to handle required field but it seems to don't call readonly_cssclass_adder. But I found an other and easyer solution, my readOnly widget automatically turned readOnly ctrlHolder

此添加是我现在最喜欢的回复:

This addition is my favorite response for now:

编辑2:我最后选择的另一种方法是覆盖不调用BoundField.label_tag的 uni_form / field.html 模板。所以我检查了这里的字段状态。

edit 2: The other way I choose at end was to "override" the uni_form/field.html template which don't call BoundField.label_tag. So I checked here field state.

<label for="{{ field.auto_id }}"{% if field.field.required %}
       class="requiredField{% if field.widget.attrs.readonly %} readOnlyLabel{% endif %}"
       {% else %}{% if field.widget.attrs.readonly %}class="readOnlyLabel"{% endif %}{% endif %}>
    {{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
</label>

这篇关于如何在django表单声明中设置一个标签的css类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆