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')
添加回答
举报