Django Admin表单 - 如何覆盖MultiSelectField类?

时间:2022-11-13 19:18:04

I'm struggling with a rendering issue using Django Grappelli and Django Multiselectfield together in the admin-site. The checkbox labels are misaligned:

我正在努力解决在管理站点中使用Django Grappelli和Django Multiselectfield的渲染问题。复选框标签未对齐:

Django Admin表单 - 如何覆盖MultiSelectField类?

Grappelli defines two CSS classes:

Grappelli定义了两个CSS类:

.aligned label {
    display: block; float: left;
    padding: 0 10px 6px 0;
    width: 120px;
}
.aligned .vCheckboxLabel {
    display: inline; float: none; clear: both;
    margin: 0 0 0 10px; padding: 0;
}

If I change the checkbox class to ".vCheckboxLabel" in the browser console, the labels are aligned correctly and there's no issue. However, I can't for the life of me find how to set the class in the admin template.

如果我在浏览器控制台中将复选框类更改为“.vCheckboxLabel”,则标签正确对齐并且没有问题。但是,我不能为我的生活找到如何在管理模板中设置类。

Using {% if field.is_checkbox %} in the Django admin template doesn't work because it's a multiselectfield, which is instead rendered as a list of checkboxes in {{ field.field }}.

在Django管理模板中使用{%if field.is_checkbox%}不起作用,因为它是一个多选字段,而是呈现为{{field.field}}中的复选框列表。

How can I specify or override the class for MultiSelectField checkboxes in the template or elsewhere?

如何在模板或其他位置指定或覆盖MultiSelectField复选框的类?

1 个解决方案

#1


1  

Add vCheckboxLabel in Model or Form class where you are defining that form. If you are defining form using Form class then use:

在要定义该表单的Model或Form类中添加vCheckboxLabel。如果您使用Form类定义表单,请使用:

myfield = forms.BooleanField(widget=forms.CheckboxInput(attrs={'class':'vCheckboxLabel'}))

If you are using models then add widget to the column. https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#specifying-widgets-to-use-in-the-form-with-widgets

如果您使用的是模型,则将小部件添加到列中。 https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#specifying-widgets-to-use-in-the-form-with-widgets

Alternate: For simplicity you can use java script on that page. Select checkbox class and change it to vCheckboxLabel. But it is not recommended.

备用:为简单起见,您可以在该页面上使用java脚本。选择复选框类并将其更改为vCheckboxLabel。但不建议这样做。

#1


1  

Add vCheckboxLabel in Model or Form class where you are defining that form. If you are defining form using Form class then use:

在要定义该表单的Model或Form类中添加vCheckboxLabel。如果您使用Form类定义表单,请使用:

myfield = forms.BooleanField(widget=forms.CheckboxInput(attrs={'class':'vCheckboxLabel'}))

If you are using models then add widget to the column. https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#specifying-widgets-to-use-in-the-form-with-widgets

如果您使用的是模型,则将小部件添加到列中。 https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#specifying-widgets-to-use-in-the-form-with-widgets

Alternate: For simplicity you can use java script on that page. Select checkbox class and change it to vCheckboxLabel. But it is not recommended.

备用:为简单起见,您可以在该页面上使用java脚本。选择复选框类并将其更改为vCheckboxLabel。但不建议这样做。