設計一個ActionForm的驗證機制需要考慮以下幾個方面:
以下是一個簡單的ActionForm驗證機制的示例:
from django import forms
class MyForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
age = forms.IntegerField(min_value=0, max_value=100)
def clean(self):
cleaned_data = super().clean()
name = cleaned_data.get("name")
email = cleaned_data.get("email")
age = cleaned_data.get("age")
if not name:
self.add_error("name", "Name is required.")
if not email:
self.add_error("email", "Email is required.")
if not age:
self.add_error("age", "Age is required.")
if age < 0 or age > 100:
self.add_error("age", "Age must be between 0 and 100.")
在這個示例中,我們定義了一個包含三個字段(name、email和age)的表單。然后,我們在clean
方法中使用add_error
方法來添加錯誤消息,如果用戶輸入的數據不符合驗證規則。