3

このウィジェットを作成しました

class DateTimeWidget(forms.TextInput):
  attr = {'class': 'datetimepicker'}
  class Media:
    js = ('js/jquery-ui-timepicker-addon.js',)

次に、フォームで使用します

class SessionForm(forms.ModelForm):
  class Meta:
    model = Session
  def __init__(self, *args, **kwargs):
    super(SessionForm, self).__init__(*args, **kwargs)
    self.fields['start_time'].widget = DateTimeWidget()
    self.fields['end_time'].widget = DateTimeWidget()

class私のフィールドにはcss が適用されていません( &の両方にdatetimepickerが適用されることを期待しています)。 私は間違った場所に置いたと思います。どこで指定すればよいですか?start_timeend_time
attr

4

2 に答える 2

5

Firstly, the html attributes are stored in widget.attrs, not attr.

Secondly, you can't declare attrs = {'class': 'datetimepicker'} in your widget definition, because the __init__ method will overwrite self.attrs.

Instead, you can set the attrs in the __init__ method.

Here's a rather naive implementation. You might want to add some extra checks to make sure you don't overwrite any existing items in kwargs['attrs']. Note that we have subclassed DateTimeInput instead of TextInput.

class DateTimeWidget(DateTimeInput):
    def __init__(self, *args, **kwargs):
        kwargs['attrs'] = {'class': 'datepicker'}
        super(DatePickerWidget, self).__init__(*args, **kwargs)
于 2012-03-28T13:02:18.033 に答える
3

複数の問題があります。

  • 属性をオーバーライドするには、init をオーバーライドして属性を更新する必要があります。または、ウィジェットを初期化するときに attrs を指定できます。参照: https://github.com/django/django/blob/master/django/forms/widgets.py#L163

  • ウィジェットは次のように定義することもできます:

.

class SessionForm(forms.ModelForm):
    class Meta:
        model = Session
        widgets = {'start_time': DateTimeWidget(),
                   'end_time': DateTimeWidget()}
于 2012-03-28T11:26:17.233 に答える