カスタムフォームでは、モデルのフィールドの一意性(つまり、unique=True
が設定されている)をどのように検証しますか?ModelFormを使用せずにunique = Trueフィールドを検証/クリーン()する方法は?
私はdjangoのModelFormがBaseModelFormのclean()
メソッド内で呼び出されるvalidate_unique()
関数を自動的に実行することを知っています.ModelFormを使用すると、これは(管理者の場合と同様に)正しく処理されます。
しかし、私は自分のフォームを一から作成しています。これをどうやって自分で処理できるのでしょうか?私は
...私の最大の障害とは、データがクリーニングされているときに、フォームに添付されているオブジェクトを知っていると思ういくつかのコード:
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の代わりにカスタムフォームを作成する理由はありますか? – tghw
私は別のアプリからのもので、同じEditUserProfileFormで処理される必要がある "通知"フィールドを表示するようにコードを更新しました。私は複数のモデルソースからModelFormを作ることはできないと思っています... – thornomad