============== ウィジェット ============== :revision-up-to: 17812 (1.4) unfinished .. module:: django.forms.widgets :synopsis: Django の組み込みフォームウィジェットです。 .. currentmodule:: django.forms ウィジェットとは、Django で HTML の入力エレメントを表現するためのオブジェク トです。ウィジェットは、 HTML のレンダリングや、個々のウィジェットに対応す るデータをGET/POST 辞書から抽出する処理を行います。 ウィジェットの指定 ------------------ フォームに何らかのフィールドを作成する場合、 Django は表示するデータの型に 応じて適切なデフォルトのウィジェットを使います。どのフィールドがどのウィ ジェットを使っているかは、 :ref:`組み込みフィールドクラス ` のドキュメントを参照してください。 とはいえ、デフォルトとは違うウィジェットを使いたい場合もあるでしょう。その 場合には、以下の例のように、フィールドを定義する際に :attr:`~Field.widget` 引数を指定します:: from django import forms class CommentForm(forms.Form): name = forms.CharField() url = forms.URLField() comment = forms.CharField(widget=forms.Textarea) 上のコードでは、 comment フィールドにデフォルトの :class:`TextInput` ウィジェッ トではなく、より大きな :class:`Textarea` ウィジェットを使うように指定しています。 .. Setting arguments for widgets ----------------------------- ウィジェットに引数を設定する ---------------------------- .. Many widgets have optional extra arguments; they can be set when defining the widget on the field. In the following example, the :attr:`~SelectDateWidget.years` attribute is set for a :class:`~django.forms.extras.widgets.SelectDateWidget`:: 多くのウィジェットにはオプションの追加引数があり、それらはフィールドの ウィジェットを定義する際に設定できます。次の例では、 :attr:`~SelectDateWidget.years` 属性が :class:`~django.forms.extras.widgets.SelectDateWidget` に設定されます:: from django.forms.fields import DateField, ChoiceField, MultipleChoiceField from django.forms.widgets import RadioSelect, CheckboxSelectMultiple from django.forms.extras.widgets import SelectDateWidget BIRTH_YEAR_CHOICES = ('1980', '1981', '1982') GENDER_CHOICES = (('m', 'Male'), ('f', 'Female')) FAVORITE_COLORS_CHOICES = (('blue', 'Blue'), ('green', 'Green'), ('black', 'Black')) class SimpleForm(forms.Form): birth_year = DateField(widget=SelectDateWidget(years=BIRTH_YEAR_CHOICES)) gender = ChoiceField(widget=RadioSelect, choices=GENDER_CHOICES) favorite_colors = forms.MultipleChoiceField(required=False, widget=CheckboxSelectMultiple, choices=FAVORITE_COLORS_CHOICES) .. See the :ref:`built-in widgets` for more information about which widgets are available and which arguments they accept. どのようなウィジェットが利用可能で、それらがどの引数を受け付けるかについては、 :ref:`built-in widgets` を参照してください。 .. Widgets inheriting from the Select widget ----------------------------------------- Select ウィジェットを継承するウィジェット ----------------------------------------- .. Widgets inheriting from the :class:`Select` widget deal with choices. They present the user with a list of options to choose from. The different widgets present this choice differently; the :class:`Select` widget itself uses a ```` を、 :class:`RadioSelect` はラジオボタンを使う、という具合です。 .. :class:`Select` widgets are used by default on :class:`ChoiceField` fields. The choices displayed on the widget are inherited from the :class:`ChoiceField` and changing :attr:`ChoiceField.choices` will update :attr:`Select.choices`. For example:: :class:`Select` ウィジェットはデフォルトで :class:`ChoiceField` フィールド によって使われます。このウィジェットは表示する選択肢を :class:`ChoiceField` から継承しており、 :attr:`ChoiceField.choices` を変更すると :attr:`Select.choices` も更新されます。例えば:: >>> from django import forms >>> CHOICES = (('1', 'First',), ('2', 'Second',))) >>> choice_field = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) >>> choice_field.choices [('1', 'First'), ('2', 'Second')] >>> choice_field.widget.choices [('1', 'First'), ('2', 'Second')] >>> choice_field.widget.choices = () >>> choice_field.choices = (('1', 'First and only',),) >>> choice_field.widget.choices [('1', 'First and only')] .. Widgets which offer a :attr:`~Select.choices` attribute can however be used with fields which are not based on choice -- such as a :class:`CharField` -- but it is recommended to use a :class:`ChoiceField`-based field when the choices are inherent to the model and not just the representational widget. :attr:`~Select.choices` 属性を持つウィジェットは、実は選択肢を扱わないフィールド -- 例えば :class:`CharField` -- に対して使うことも可能ですが、本質的にその 選択肢がモデル由来であり、かつ表示目的だけのウィジェットでもないならば、 :class:`ChoiceField` ベースのフィールドに対して使うことを推奨します。 ウィジェットインスタンスのカスタマイズ -------------------------------------- ウィジェットを HTML としてレンダリングする際、 Django は最小限の HTML しか 出力しません。すなわち、クラス定義やウィジェット固有の属性は一切付加しない のです。従って、例えばページ上にまったく同じ見栄えの :class:`TextInput` ウィジェットが並ぶわけです。 ウィジェットごとに見栄えを変えたいのなら、各々のウィジェットに属性を指定し てやる必要があります。ウィジェットを指定するときに、レンダリング後の HTML に付加したい属性のリストを指定できます。 例えば、以下のような簡単なフォームを考えましょう:: from django import forms class CommentForm(forms.Form): name = forms.CharField() url = forms.URLField() comment = forms.CharField() このフォームは 3 つの :class:`TextInput` ウィジェットからなり、デフォルトの レンダリングでは CSS クラスや属性は指定されていません。従って、各ウィジェットは 全く同じ入力ボックスとしてレンダリングされます:: >>> f = CommentForm(auto_id=False) >>> f.as_table() Name: Url: Comment: 現実の Web ページでは、全ウィジェットが同じに見えるような見栄えを期待しない でしょう。コメント欄をもうちょっと大きな入力ボックスにしたかったり、 ``'name'`` ウィジェットに特別な CSS クラスを指定したかったりするかもしれま せん。そうするには、ウィジェット作成時に :attr:`Widget.attrs` 属性を使用します: 例えば:: class CommentForm(forms.Form): name = forms.CharField( widget=forms.TextInput(attrs={'class':'special'})) url = forms.URLField() comment = forms.CharField( widget=forms.TextInput(attrs={'size':'40'})) これで、 Django はレンダリング結果に追加の属性を組み込むようになります: >>> f = CommentForm(auto_id=False) >>> f.as_table() Name: Url: Comment: .. _built-in widgets: 組み込みウィジェット -------------------- Django は、基本的な HTML ウィジェットすべてと、よく使われるウィジェットグルー プを提供しています: ``Widget`` ~~~~~~~~~~ .. class:: Widget .. This abstract class cannot be rendered, but provides the basic attribute :attr:`~Widget.attrs`. この抽象クラスはレンダリングできませんが、基本の属性 :attr:`~Widget.attrs` を提供します。 .. attribute:: Widget.attrs .. A dictionary containing HTML attributes to be set on the rendered widget. レンダリングされるウィジェットに設定される HTML 属性を含んだ辞書です。 .. code-block:: python >>> name = forms.TextInput(attrs={'size': 10, 'title': 'Your name',}) >>> name.render('name', 'A name') u'' ``TextInput`` ~~~~~~~~~~~~~ .. class:: TextInput テキスト入力: ```` です。 ``PasswordInput`` ~~~~~~~~~~~~~~~~~ .. class:: PasswordInput パスワードテキスト入力: ```` です。 .. Takes one optional argument: オプションの引数を一つ取ります。 .. attribute:: PasswordInput.render_value .. Determines whether the widget will have a value filled in when the form is re-displayed after a validation error (default is ``False``). 検証エラー後にウィジェットが再表示される際、値が記入されるかどうかを 決定します (デフォルトは ``False`` です)。 .. .. versionchanged:: 1.3 The default value for :attr:`~PasswordInput.render_value` was changed from ``True`` to ``False`` .. versionchanged:: 1.3 :attr:`~PasswordInput.render_value` のデフォルト値は ``True`` から ``False`` に変更されました。 ``HiddenInput`` ~~~~~~~~~~~~~~~ .. class:: HiddenInput hidden ウィジェット: ```` です。 ``MultipleHiddenInput`` ~~~~~~~~~~~~~~~~~~~~~~~ .. class:: MultipleHiddenInput 複数の hidden ウィジェット: ```` です。 .. A widget that handles multiple hidden widgets for fields that have a list of values. 複数の値を持つフィールド用に、複数の hidden ウィジェットを使うウィジェット です。 .. attribute:: MultipleHiddenInput.choices .. This attribute is optional when the field does not have a :attr:`~Field.choices` attribute. If it does, it will override anything you set here when the attribute is updated on the :class:`Field`. この属性は、フィールドに :attr:`~Field.choices` 属性が無い場合には 指定する必要はありません。もし属性がある場合、 :class:`Field` で `choices` 属性が更新されると、ここでの指定は上書きされます。 ``FileInput`` ~~~~~~~~~~~~~ .. class:: FileInput ファイルアップロード: ```` です。 ``ClearableFileInput`` ~~~~~~~~~~~~~~~~~~~~~~ .. class:: ClearableFileInput .. versionadded:: 1.3 .. File upload input: ````, with an additional checkbox input to clear the field's value, if the field is not required and has initial data. フィールドが入力必須ではなく、かつ初期データがある場合に、フィールドの値を クリアするためのチェックボックスを備えたファイルアップロード入力: ```` です。 ``DateInput`` ~~~~~~~~~~~~~ .. class:: DateInput .. Date input as a simple text box: ```` 単純なテキストボックスで表現された、日付用の入力ウィジェット: ```` です。 .. Takes one optional argument: オプションの引数を一つ取ります: .. attribute:: DateInput.format .. The format in which this field's initial value will be displayed. フィールド初期値の表示に使う書式。 .. If no ``format`` argument is provided, the default format is the first format found in :setting:`DATE_INPUT_FORMATS` and respects :ref:`format-localization`. ``format`` 引数が指定されない場合、デフォルトの書式は :setting:`DATE_INPUT_FORMATS` で最初に見つかった書式になり、かつ :ref:`format-localization` が適用されます。 ``DateTimeInput`` ~~~~~~~~~~~~~~~~~ .. class:: DateTimeInput 単純なテキストボックスで表現された、日付/時刻用の入力ウィジェット: ```` です。 .. Takes one optional argument: オプションの引数を一つ取ります: .. attribute:: DateTimeInput.format .. The format in which this field's initial value will be displayed. フィールド初期値の表示に使う書式。 .. If no ``format`` argument is provided, the default format is the first format found in :setting:`DATETIME_INPUT_FORMATS` and respects :ref:`format-localization`. ``format`` 引数が指定されない場合、デフォルトの書式は :setting:`DATETIME_INPUT_FORMATS` で最初に見つかった書式になり、かつ :ref:`format-localization` が適用されます。 ``TimeInput`` ~~~~~~~~~~~~~ .. class:: TimeInput .. Time input as a simple text box: ```` 単純なテキストボックスで表現された、時刻用の入力ウィジェット: ```` です。 .. Takes one optional argument: オプションの引数を一つ取ります: .. attribute:: TimeInput.format .. The format in which this field's initial value will be displayed. フィールド初期値の表示に使う書式。 .. If no ``format`` argument is provided, the default format is the first format found in :setting:`TIME_INPUT_FORMATS` and respects :ref:`format-localization`. ``format`` 引数が指定されない場合、デフォルトの書式は :setting:`TIME_INPUT_FORMATS` で最初に見つかった書式になり、かつ :ref:`format-localization` が適用されます。 ``Textarea`` ~~~~~~~~~~~~ .. class:: Textarea テキストエリア: ```` です。 ``CheckboxInput`` ~~~~~~~~~~~~~~~~~ .. class:: CheckboxInput チェックボックス: ```` です。 .. Takes one optional argument: オプションの引数を一つ取ります: .. attribute:: CheckboxInput.check_test .. A callable that takes the value of the CheckBoxInput and returns ``True`` if the checkbox should be checked for that value. CheckboxInput の値を受け取り、チェックボックスにチェックを入れるべき ならば ``True`` を返す呼び出し可能オブジェクト。 ``Select`` ~~~~~~~~~~ .. class:: Select セレクタ: ```` です。 .. attribute:: Select.choices .. This attribute is optional when the field does not have a :attr:`~Field.choices` attribute. If it does, it will override anything you set here when the attribute is updated on the :class:`Field`. この属性は、フィールドに :attr:`~Field.choices` 属性が無い場合には 指定する必要はありません。もし属性がある場合、 :class:`Field` で `choices` 属性が更新されると、ここでの指定は上書きされます。 ``NullBooleanSelect`` ~~~~~~~~~~~~~~~~~~~~~ .. class:: NullBooleanSelect 「不明」, 「はい」, 「いいえ」 を選択肢とするセレクタです。 ``SelectMultiple`` ~~~~~~~~~~~~~~~~~~ .. class:: SelectMultiple .. Similar to :class:`Select`, but allows multiple selection: ```` :class:`Select` と似ていますが、複数選択が可能なセレクタ: ```` です。 ``RadioSelect`` ~~~~~~~~~~~~~~~ .. class:: RadioSelect .. Similar to :class:`Select`, but rendered as a list of radio buttons within ``
  • `` tags: :class:`Select` と似ていますが、 ``
  • `` タグを使ったラジオボタンのリスト としてレンダリングされます: .. code-block:: html .. versionadded:: 1.4 .. For more granular control over the generated markup, you can loop over the radio buttons in the template. Assuming a form ``myform`` with a field ``beatles`` that uses a ``RadioSelect`` as its widget: 生成されるマークアップをもっと細かくコントロールしたければ、テンプレート内で ラジオボタンに対してループを回すことができます。仮に ``myform`` という フォームがあり、そこに ``RadioSelect`` をウィジェットに指定した ``beatles`` というフィールドがあると仮定すると: .. code-block:: html+django {% for radio in myform.beatles %}
    {{ radio }}
    {% endfor %} .. This would generate the following HTML: これは次の HTML を生成します: .. code-block:: html
    .. That included the ``