😺

[Django]FKのModelChoiceFieldでのValidationエラーの回避法

2024/03/07に公開

概要

DjangoのModelにてForeignKeyを設定している項目のデータベース登録において発生するバリデーションエラーの対応方法を紹介。

環境

Python 3.12.2
Django 5.0.2

エラーメッセージ

Select a valid choice. That choice is not one of the available choices.

原因

Forms.pyの下記コードにて、Objects.none()としているため、バリデーションにて選択肢の候補が取得できず、画面上でどの選択肢を選んでも有効でない判定となっていた。

# Forms.py
MyColumn = CustomModelChoiceField(queryset=MyRelatedClass.objects.none(), empty_label='', required=True)

対応方法

querysetにてobjects.allあるいはobjects.filter()にて選択肢の検索を行う
変更前

# Forms.py
MyColumn = CustomModelChoiceField(queryset=MyRelatedClass.objects.none(), empty_label='', required=True)

変更後

# Forms.py
MyColumn = CustomModelChoiceField(queryset=MyRelatedClass.objects.all(), empty_label='', required=True)
# あるいは
MyColumn = CustomModelChoiceField(queryset=MyRelatedClass.objects.filter(mycolumn = "my_filter_condition"), empty_label='', required=True)

備考

ModelChoiceFieldではなく、OverrideしたCustomModelChoiceFieldを使用している理由は別記事で記載予定

Discussion