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

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

问题描述

我正在使用 django-uniform 并使用一些统一的功能,我正在寻找一种方法来直接从表单声明中添加 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))

我现在唯一的方法是在我的通用表单模板上添加一些 javascript 并手动添加类.

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.但是我找到了另一个更简单的解决方案,我的只读小部件自动变为只读 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天全站免登陆