首页 > 解决方案 > 自定义 Django 表单验证器不会在前端呈现验证错误

问题描述

我有一个自定义验证器,如果验证失败,它应该在前端为用户引发错误。但是,我不确定在哪里以及如何将其返回到frontend。现在它只显示在开发服务器上的终端/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

标签: pythondjango

解决方案


要在表单中显示错误,您必须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,它正是为此目的而设计的。它将节省您编写大量代码。


推荐阅读