0
0

More than 3 years have passed since last update.

【Django】forms.pyでログインユーザーに応じてテキストフィールドをdisabledしたい

Posted at

ログインユーザーに応じてフォームのあるフィールドを入力不可にしたい。

参考
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)
...

勉強不足なのでもっと良い書き方があったら教えてください。

0
0
1

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
0