LoginSignup
0
1

More than 1 year has passed since last update.

【Django】フォームを無効化(読み取り専用)にする方法

Last updated at Posted at 2022-01-01

やりたいこと

・Formの無効化
・サーバーに送信された場合でも受け取った値を無視する

ModelFormの場合

from django import forms
from .models import Sample

class SampleForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        self.fields['hoge'].disabled = True
        super().__init__(*args, **kwargs)

    class Meta:
        model = Sample

Formの場合

from django import forms

class SampleForm(forms.Form):
    hoge = forms.CharField(disabled=True)

もしくは

from django import forms

class SampleForm(forms.Form):
    hoge = forms.CharField(label='hoge')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['hoge'].disable = True

参考資料

公式サイトの内容を日本語訳しました。

disabledブール引数をTrueに設定すると、HTMLのdisable属性を使用してフォームフィールドが無効になり、ユーザーが編集できなくなります。
ユーザーがサーバーに送信されたフィールドの値を改ざんしたとしても、無視してフォームの初期データの値を優先します。

Djangoドキュメント

0
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
0
1