ログインユーザーに応じてフォームのあるフィールドを入力不可にしたい。
参考
https://qiita.com/The-town/items/4b5718ccfc488edd93c8
Formのインスタンス作成時にuserを渡してもらう
forms.py
class Form(forms.ModelForm):
def __init__(self, user, *args, **kwargs):
self.current_user = user
super().__init__(*args, **kwargs)
for field in self.fields.values():
if str(self.current_user) == "hoge": # hogeならdisabled
field.widget.attrs["disabled"] = ""
class Meta:
model = Hoge
fields = ('お好きなフィールド')
views.pyでFormインスタンスを作成する際、引数としてログインしているユーザー情報を渡す。
views.py
class View(View):
...
form = Form(user=request.user, data=request.POST)
...
勉強不足なのでもっと良い書き方があったら教えてください。