1
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] 管理画面にバリデーションを実装する

Last updated at Posted at 2023-04-21

はじめに(前提)

  • Django公式チュートリアルのソースを元にしています。
  • 管理画面側のモデルにバリデーションを実装する方法をまとめています。

モデル

  • Question
  • Choice(←今回バリデーションを実装するモデル)

やりたいこと

  • VOTESが負数の場合に、バリデーションエラーを実装したい。
    • 現状は負数の場合でも保存されてしてしまう。

スクリーンショット 2023-04-21 17.41.36.png

実装

  • 実装したいモデルのClasscleanメソッドを追加する
# models.py
class Choice(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)

    def __str__(self) -> str:
        return self.choice_text

    # この行以下を追加
    def clean(self):
        if (self.votes < 0):
            raise ValidationError({"votes": "投票数は0以上で入力してください。"})

できた!
スクリーンショット 2023-04-26 15.20.03.png

補足

以下のように記載してしまうと、参考画像のように、バリデーションエラーメッセージがCHOICE TEXTの下に表示されてしまう。

raise ValidationError("投票数は0以上で入力してください。")

エラーメッセージの表示位置を固定するために{"field_name": "error_message"}としている。

[参考画像]
スクリーンショット 2023-04-21 17.59.15.png

参考

終わりに

  • まだDjangoについて勉強し始めたばかりなので、「こっちの書き方の方が良いよ」などあればコメントください。

以上

1
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
1
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?