自定义Django表单验证器不会在前端显示验证错误



我有一个自定义验证器,如果验证失败,它应该在前端为用户引发错误。然而,我不确定在哪里以及如何将其返回到前端。现在它只显示在开发服务器的终端/Django错误站点:

视图:

def raise_poller(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = PollersForm(request.POST)
# check whether it's valid:
if form.is_valid():
# Make Validation of Choices Fields
poller_choice_one = form.cleaned_data['poller_choice_one']
poller_choice_two = form.cleaned_data['poller_choice_two']
if ' ' in poller_choice_one or ' ' in poller_choice_two:
raise ValidationError('Limit your choice to one word', code='invalid')
return poller_choice_two  # !! IDE says this is unreachable
else:
# process the remaining data in form.cleaned_data as required
poller_nature = form.cleaned_data['poller_nature']
poller_text = form.cleaned_data['poller_text']
poller_categories = form.cleaned_data['poller_categories']
# Get the user
created_by = request.user
# Save the poller to the database
p = Pollers(poller_nature=poller_nature,
poller_text=poller_text,
poller_choice_one=poller_choice_one,
poller_choice_two=poller_choice_two,
created_by=created_by)
p.save()
p.poller_categories.set(poller_categories)
# redirect to a new URL:
return HttpResponseRedirect('/')
# if a GET (or any other method) we'll create a blank form
else:
form = PollersForm()
return render(request, 'pollinator/raise_poller.html', {'form': form})

模板

{% block content %}
<div class="poll-container">
<form action="/raisepoller/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
</div>

{% endblock %}

也在哪里最好的结构/实现自定义验证器?在if form.is_valid部分之后?

要显示表单中的错误,您必须在表单(而不是视图)中引发ValidationError,因为表单期望并处理ValidationError最终被引发。在这里阅读关于表单验证的文档

class PollersForm(forms.Form):

def clean(self):
data = self.cleaned_data
poller_choice_one = data['poller_choice_one']
poller_choice_two = data['poller_choice_two']
if ' ' in poller_choice_one or ' ' in poller_choice_two:
# raising ValidationError here in clean does the trick
raise ValidationError('Limit your choice to one word', code='invalid')
return data

旁注:如果您使用表单所做的唯一事情是创建模型实例,则应该考虑使用ModelForm, ModelForm正是为此目的而设计的。它将节省你写很多代码。

相关内容

  • 没有找到相关文章

最新更新