1 回答

TA貢獻1843條經驗 獲得超7個贊
要驗證表單中的唯一性,您可以在保存表單之前使用表單clean_fieldname()
方法進行額外的數據庫查詢。
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')
或者如果它應該是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')
添加回答
舉報