【发布时间】:2016-08-24 08:26:26
【问题描述】:
我使用 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)
【问题讨论】:
-
我看不到模板如何从您的
search视图接收您的搜索。 context_dict 没有填充...这里没有显示另一段代码吗?否则,将context_dict={"search_form":search_form}添加到您的视图函数可能会有所帮助。 -
这里有很多问题。请从他们的网站学习 django 教程,因为我不太明白您为什么使用上下文处理器而不是将经过验证的表单传递给模板。
标签: python django python-2.7 django-forms