cleanメソッドによるカスタムバリデーション
フィールドレベルとフォームレベルの検証ルールを追加します
「cleanメソッドによるカスタムバリデーション」はCoddyKit上の無料Django Academyレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはDjango Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Django Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Beyond Built-in Rules
Model fields give you basic checks, but real apps need custom rules. Django runs your own clean methods to enforce exactly the logic you want. 🧹
Field-Level clean
To validate one field, add a method named clean_fieldname. Django calls it automatically during validation for that single field.
def clean_title(self):
title = self.cleaned_data["title"]
return titleRead from cleaned_data
Inside a clean method, pull the value from cleaned_data. By this point Django has already converted it to the right Python type for you.
title = self.cleaned_data["title"]Raise to Reject
If a value breaks your rule, raise a ValidationError. Django catches it and shows the message next to that field in the form.
from django.core.exceptions import ValidationError
raise ValidationError("Title is too short.")A Real Field Check
Here we reject titles shorter than five characters. Note you must return the value at the end so it stays in cleaned_data.
def clean_title(self):
title = self.cleaned_data["title"]
if len(title) < 5:
raise ValidationError("Too short.")
return titleAlways Return the Value
The golden rule of clean_fieldname: return the cleaned value. Forget it and the field becomes None, even when input was valid.
Form-Level clean
To compare two fields, override the whole-form clean method. It runs after every field-level check has finished.
def clean(self):
cleaned = super().clean()
return cleanedCall super().clean() First
Begin your form-level clean by calling super().clean(). That gives you the full cleaned_data dict gathered from the field checks.
cleaned = super().clean()
start = cleaned.get("start")
end = cleaned.get("end")Compare Two Fields
Now you can enforce cross-field rules, like making sure end comes after start. Raise ValidationError when the relationship is wrong.
if start and end and end < start:
raise ValidationError("End must be after start.")Attach Errors to a Field
In form-level clean you can target one field with add_error. The message then appears right beside that input, not at the top.
self.add_error("end", "End must be after start.")Order of Validation
Django runs each clean_fieldname first, then the form-level clean last. Knowing this order helps you place each rule in the right spot.
Quick Check
Where should a rule that compares two fields live?
Recap: Custom Validation
Well done! Use clean_fieldname for single fields and form-level clean for cross-field rules. Raise ValidationError to reject, and always return cleaned values. 🎉
よくある質問
「cleanメソッドによるカスタムバリデーション」レッスンは無料ですか?
はい。「cleanメソッドによるカスタムバリデーション」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Django Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Django Academyコースには全4レッスンが含まれています。
「cleanメソッドによるカスタムバリデーション」で何を学びますか?
フィールドレベルとフォームレベルの検証ルールを追加します ブラウザで直接実行するハンズオンコードでDjango Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Django Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのDjango Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。
「cleanメソッドによるカスタムバリデーション」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このDjango Academyレッスンでコードを書いて実行できますか?
はい。すべてのDjango Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- ModelFormとMeta.fieldsの宣言
- form.save()とcommit=False
- cleanメソッドによるカスタムバリデーション
- Widgets、Labels、Help Text