from django import forms
from django.core.exceptions import ValidationError
from readings.models import Volunteer
class VolunteerForm(forms.Form):
name=forms.CharField(min_length=5,max_length=60,label="登记名",
error_messages={"required":"请填写登记名","min_length":"登记名至少五个字符"})
age=forms.IntegerField(min_value=18,max_value=120,label="年龄")
credit=forms.DecimalField(max_digits=6,decimal_places=2,min_value=0,label="补助")
confirmation=forms.DecimalField(max_digits=6,decimal_places=2,min_value=0,label="确认补助")
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
self.clean_events=[]
def clean_name(self):
self.clean_events.append("name")
name=self.cleaned_data["name"]
if name.isdecimal():
raise ValidationError("登记名不能全是数字",code="numeric_name")
if Volunteer.objects.filter(name=name).exists():
raise ValidationError("登记名已存在",code="duplicate_name")
return name
def clean(self):
self.clean_events.append("form")
data=super().clean()
if "credit" in data and "confirmation" in data and data["credit"]!=data["confirmation"]:
raise ValidationError("两次补助金额需一致",code="mismatch")
return data
本例需在 CPython 3.12.14、Django 5.2.19、SQLite、Edge 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:CPython 3.12.14、Django 5.2.19、SQLite、Edge
入口文件:projects/django-form-component/forms.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
forms.py,或下载右侧课程工程包。 - 确认本地已准备 CPython 3.12.14、Django 5.2.19、SQLite、Edge。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a171.zip
课程关联工程包(登记关联31章) · 含当前章节或实例 · mbskycom202612a164.zip