0
0

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 1 year has passed since last update.

【Django】viewsで定義した変数やオブジェクトをformで使う

Posted at

想定した仕様

本の検索サイトの著者のプロフィール欄で、その著者が書いた本を選択できるフォームを作成。
同じformsファイルのBookFormを使っても著者によって選択肢(choices)を変える必要がある。

コード

views.py
...
def get(self, request, id):
    ...
    # 著者のidを取得して、formに渡す
    author = AuthorModel.objects.get(id=id)
    form = BookForm(author_id=author.id)
    ...
...

ポイントはフォームを宣言したときにauthor_id=author.idを引数に取っていること。
そうすればforms.pyではkwargs.pop('author_id')で取得できる。

forms.py
class BookForm(forms.Form):
    # フォームを作成
    book_select = ChoiceField(
        widget=Select(),
    )
    # 初期化関数
    def __init__(self, *args, **kwargs):
        if kwargs.get("author_id"):
            self.author_id = kwargs.pop('author_id')
        else:
            self.author_id = None
        super().__init__(*args, **kwargs)

        author = AuthorModel.objects.get(id=author_id) # 著者を取得
        books = BookModel.objects.filter(author=author) # その著者の本を取得
        books_choices = [(book.id, book.name) for book in books] # 本を配列に格納
        self.fields['book_select'].choices = books_choices # 配列をchoicesに指定

このコードで動作は確かめていないが、とにかくkwargs.pop('author_id')で取得できるんだという備忘録。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?