1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Django] forms.Form placeholderの設定

Posted at

各フィールドに一括でplaceholderを設定する場合

from django import forms


class RegistrationForm(forms.Form):
    username = forms.CharField(
        label='insert your name',
    )

    email = forms.EmailField(
        label='insert your email address',
    )

    def __init__(self, *args, **kwargs):
        super(RegistrationForm, self).__init__(*args, **kwargs)
        for field in self.fields.values():
            field.widget.attrs['placeholder'] = field.label

self.fields.values()でformの各フィールドを取得しフィールドが持つラベルをplaceholderに設定する.

フィールドごとにplaceholderを設定する場合

from django import forms


class RegistrationForm(forms.Form):
    username = forms.CharField(
        label='insert your name',
    )

    email = forms.EmailField(
        label='insert your email address',
        widget=forms.EmailInput(
            attrs={
                'placeholder': 'メールアドレスを入力してください.'
            }
        )
    )

注:EmailFieldはwidgetとして設定できないフィールドなので代わりにEmailInputを利用しています

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?