LoginSignup
9
6

More than 3 years have passed since last update.

Djangoのforms.pyでログインユーザーを取得する方法

Last updated at Posted at 2020-05-30

やりたいこと

forms.pyのFormClassの中で、現在ログインしているユーザー情報を使用して
何らかの処理を行いたい。

forms.py

class Form(forms.ModelForm):
    def method(self):
        model = Model
        model.objects.filter(user=[ログインしているユーザー]) # ログインユーザーを使いたい

解決策

views.pyでFormインスタンスを作成する際、引数としてログインしているユーザー情報を渡す。

views.py

class View(View):
...
    form = Form(user=request.user, data=request.POST)
...
forms.py
...
class Form(forms.ModelForm):
    def __init__(self, user, *args, **kwargs):
        self.current_user = user
        super().__init__(*args, **kwargs)

    def method(self):
        model = Model
        model.objects.filter(user=self.current_user)
...

使用するとき

formでバリデーションをするときに使用した。

参考

stackoverflowの質問
https://stackoverflow.com/questions/5119994/get-current-user-in-django-form

参考にした回答
https://stackoverflow.com/a/5122029

質問者
https://stackoverflow.com/users/616173/yulia

回答者
https://stackoverflow.com/users/616173/yulia

回答者

9
6
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
9
6