所以我试着添加一个简单的验证器来检查邮政编码并在用户输入非字母数字时返回验证错误。但经过尝试后,我似乎无法获得最基本的验证信息。
这是我的表单我使用示例字段验证只是为了尝试让它显示但不是
class CartAddShippingDetailsForm(forms.Form):
first_name = forms.CharField(max_length=100)
last_Name = forms.CharField(max_length=100)
email = forms.EmailField()
address1 = forms.CharField(max_length=100)
town = forms.CharField(max_length=100)
postcode = forms.CharField()
country = LazyTypedChoiceField(choices=countries)
additional_note = forms.CharField(max_length=100, required=False)
def clean_postcode(self):
data = self.cleaned_data['postcode']
if "fred@example.com" not in data:
raise forms.ValidationError("You have forgotten about Fred!")
else:
return postcode
这是我的views.py
def shipping_details(request):
cart = Cart(request)
shipping_form = CartAddShippingDetailsForm()
if request.method == 'POST':
shipping_form = CartAddShippingDetailsForm(request.POST)
if shipping_form.is_valid():
return redirect(reverse('test_order'))
else:
return render(request, 'shippingdetails.html', {'cart': cart, 'shipping_form': shipping_form})
和html
{% extends "base.html" %}
{% load static %}
{% block title %}Shipping{% endblock %}
{% block content %}
<form action="{% url 'test_order' %}" method="post">
<div class="colcontainer">
{% csrf_token %}
{{ shipping_form }}
<input type="submit" name="Submit">
</div>
</form>
{% endblock %}
我也尝试过使用验证器,因为我只想检查字段是否只包含字母数字符号
postcode = forms.CharField(validators=[validators.validate_slug])
但根本没有显示,表单通过验证并成功重定向。我已经尝试了一切,似乎没有任何工作。我是否需要额外的HTML代码来显示验证错误?我在文档中找不到任何关于它的东西,它让我疯狂!