In a custom Form, how does one validate a Model's field's uniqueness (i.e., has unique=True
set)?
I know that django's ModelForm automatically performs a validate_unique()
function that is called within the BaseModelForm's clean()
method -- so, when using ModelForm, this will be handled correctly (as it is in the Admin).
However, I am creating my own form from scratch and wonder how I can go about handling this myself? I think my biggest stumbling block is knowing which object is attached to the form when the data is being cleaned ...
Some code:
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