Django在基本模板中形成。如何显示验证错误?

时间:2016-08-24 08:26:27

标签: python django python-2.7 django-forms

我使用Django 1.8.14。我的网站每个页面都有Search表单。我通过上下文处理器将Search表单传递给基本模板。每次表单都将数据发送到/search/视图。而且有一个问题。 Django在表单上引发ValidationError,但它不显示在任何地方。当表单通过上下文处理器传递给基本模板并将数据发送到一个视图时,在模板中显示表单错误的正确方法是什么?

form.py

class SearchForm(forms.Form):
    search = forms.CharField(required = True,
                          max_length=255,
                          widget = forms.TextInput({'class':'form-control', 'type':'search','required':''})
)

   def clean_search(self):
     search = self.cleaned_data.get("search")
     regex = myregex
     if not re.match(regex, search):
         print("ValidationError")
         raise forms.ValidationError(u'Please enter a valid value')
     return search

上下文处理器:

from myproject.forms import SearchForm

def form_context(request):
   context_dict = {}
   context_dict['search_form'] = SearchForm()
   return(context_dict)

我的基本模板:

 <form method="post" action="/search/">               
     {% csrf_token %}
     {{ search_form.non_field_errors }}
     {{ search_form.errors }}
     {{ search_form.search }}
     {{ search_form.search.errors }}        
     <button type="submit" class="btn btn-find">Search</button>
 </form>

我的搜索观点:

def search(request, template):    
    if request.method == 'POST':
        search_form = SearchForm(request.POST)
        if search_form.is_valid():
           domen = search_form.cleaned_data['search']
           try:
              site = SitePage.objects.get(domen=domen)
              path="/"+site.domen +"/"
              return HttpResponseRedirect(path)
           except:
            site = None
        else:
            print search_form.errors
return render(request, template, context_dict)

2 个答案:

答案 0 :(得分:1)

一旦绑定到数据(POST请求)并验证,您需要传递表单;现在你的上下文只有一个空白表格,这就是没有错误显示的原因。

from django.shortcuts import redirect

def search(request, template):
    search_form = SearchForm(request.POST or None, request.FILES or None)

    if search_form.is_valid():
       domen = search_form.cleaned_data['search']
       results = SitePage.objects.filter(domen=domen)
       if results.exists():
          return redirect('/{}/'.format(results.domen))

    return render(request, template, {'form': search_form})

答案 1 :(得分:1)

如果你Django正在提出validation error你想要的方式,现在你所需要的只是显示html templates上的验证错误然后我想你正在寻找什么for是 Django消息

请参阅相同的官方文档 - &gt; https://docs.djangoproject.com/en/1.8/ref/contrib/messages/