【发布时间】:2009-10-12 23:23:50
【问题描述】:
在自定义表单中,如何验证模型字段的唯一性(即是否设置了unique=True)?
我知道 django 的 ModelForm 会自动执行 validate_unique() 函数,该函数在 BaseModelForm 的 clean() 方法中调用——因此,在使用 ModelForm 时,这将得到正确处理(就像在 Admin 中一样)。
但是,我正在从头开始创建自己的表单,并且想知道如何自己处理这个问题?我认为我最大的绊脚石是在清理数据时知道哪个对象附加到表单...
一些代码:
class UserProfile(CreatedModifiedModel):
user = models.ForeignKey(User, unique=True)
display_name = models.CharField('Display Name',max_length=30,
blank=True,unique=True)
class EditUserProfileForm(forms.Form):
display_name = forms.CharField(required=False,max_length=30)
# "notifications" are created from a different model, not the UserProfile
notifications = forms.MultipleChoiceField(
label="Email Notifications",
required=False,
widget=forms.CheckboxSelectMultiple,)
def clean_display_name(self):
# how do I run my own validate_unique() on this form?
# how do I know which UserProfile object I am working with?
# more code follows, including the __init__ which sets up the notifications
【问题讨论】:
-
您是否有任何理由制作自定义表单而不是 ModelForm?
-
我更新了代码以显示我需要的“通知”字段来自不同的应用程序,但在同一个 EditUserProfileForm 上处理......希望这是有道理的。我不认为我可以从多个模型来源制作 ModelForm ...
标签: django django-forms