我必须验证一个字段是否唯一。我没有在模型中使用unique = True。我在表单中使用clean()和clean_(),但引发了不同的错误。
forms.py 情况1:clean()
name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter Package Name', 'class': 'form-control'}))
def clean(self):
name = self.cleaned_data.get('name')
if Package.objects.filter(name=name):
raise ValidationError(_("Package with this package name already exist."))
return name
情况2:clean_name()
name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Enter Package Name', 'class': 'form-control'}))
def clean_name(self):
name = self.cleaned_data.get('name')
if Package.objects.filter(name=name):
raise ValidationError(_("Package with this package name already exist."))
return name
views.py
def create_package(request):
if request.method == 'POST':
form = CreatePackageForm(request.POST)
if form.is_valid():
package = Package()
package.name = form.clean()
if request.POST.get('subscription', False):
package.subscription = True
package.billing = request.POST['billing']
package.billing_after = str(request.POST['billing_days']) +' '+ request.POST['billing_unit']
else:
package.subscription = False
package.save()
return redirect('packages')
else:
form = CreatePackageForm()
context = {
'form': form,
}
return render(request, 'fitness/create_package.html', context)
在html模板中:
<p style="color:red;">{{ form.non_field_errors.as_text }}</p>
问题: 在第一种情况下,如果我发送重复的名称,但如果名称是唯一的,则验证是正确的,这会出现此错误:
'str' object has no attribute 'get'
在情况2中: 如果名称有效,则一切正常。数据正常保存,但如果是重复数据,则不会显示错误消息。但是验证仍在进行,因为它没有提交表单。