如何在 Django 中将 css 类 应用到 TimeDurationWidget

How to apply css classes to the TimeDurationWidget in Django

我正在尝试将 css 样式应用于我的模型。

from durationwidget.widgets import TimeDurationWidget

class WeightDistanceTimeModelForm(forms.ModelForm):
    weight = forms.DecimalField(widget=forms.NumberInput(attrs={'placeholder': 'Weight', 'class': 'form-control', 'step': 2.5}))
    distance = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder': 'Distance', 'class': 'form-control'}))
    time = forms.DurationField(widget=TimeDurationWidget(show_days=False, show_hours=True, show_minutes=True, show_seconds=True), required=False)

我的体重和距离字段显示了我想要的方式,但有谁知道我如何将占位符和 form-control 的 class 应用于每个 hoursminutesseconds。我似乎无法在任何地方找到任何解释这一点的文档。或者,是否有更好的方式来显示此信息?

我也试过将 class 直接添加到我的模板中:

<div class="form-control">
    {{ form.time }}
</div>

但这也没用

您可以将自定义属性应用到 TimeDurationWidget,就像您已经将它们应用到 NumberInputWidget 一样:

time = forms.DurationField(widget=TimeDurationWidget(attrs={'class': 'form-control'}, show_days=False, show_hours=True, show_minutes=True, show_seconds=True), required=False)

您甚至可以在其中硬编码一些又快又脏的 CSS(不推荐):

time = forms.DurationField(widget=TimeDurationWidget(attrs={'style': 'border: 10px dotted red'}, show_days=False, show_hours=True, show_minutes=True, show_seconds=True), required=False)

这些都记录在 Django's Widget documentation:

On a real Web page, you probably don’t want every widget to look the same. You might want a larger input element for the comment, and you might want the ‘name’ widget to have some special CSS class. It is also possible to specify the ‘type’ attribute to take advantage of the new HTML5 input types. To do this, you use the Widget.attrs argument when creating the widget: