1 回答

TA貢獻(xiàn)1843條經(jīng)驗(yàn) 獲得超7個贊
要驗(yàn)證表單中的唯一性,您可以在保存表單之前使用表單clean_fieldname()
方法進(jìn)行額外的數(shù)據(jù)庫查詢。
from django import forms
from django.core.exceptions import ValidationError
class MyForm(forms.Form):
? ? username = forms.CharField()
? ? def clean_username(self):
? ? ? ? if MyModel.objects.filter(username=self.cleaned_data['username'])\
? ? ? ? ? ? ? ? .exists():
? ? ? ? ? ? raise ValidatioError('already exists')
或者如果它應(yīng)該是ModelForm:
from django import forms
from django.core.exceptions import ValidationError
from .models import MyModel
?
class MyModelForm(forms.ModelForm):
? ? class Meta:
? ? ? ? model = MyModel
? ? ? ? fields = ['username', ]
? ? def clean_username(self):
? ? ? ? if self._meta.model.objects\
? ? ? ? ? ? ? ? .filter(username=self.cleaned_data['username'])\
? ? ? ? ? ? ? ? .exists():
? ? ? ? ? ? raise ValidatioError('already exists')
添加回答
舉報