Jak sprawdzić poprawność / clean () unikalnego = True pola bez użycia ModelForm?
W niestandardowym formularzu, w jaki sposób weryfikuje się unikalność pola modelu (tj. Maunique=True
zestaw)?
Wiem, że ModelForm django automatycznie wykonujevalidate_unique()
funkcja wywoływana w BaseModelForm'sclean()
metoda - więc podczas korzystania z ModelForm będzie to obsługiwane poprawnie (tak jak w Adminie).
Jednak od podstaw tworzę własną formę i zastanawiam się, jak sobie z tym poradzić? Myślę, że moją największą przeszkodą jest wiedzieć, który obiekt jest dołączony do formularza, gdy dane są czyszczone ...
Niektóre kody:
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