http://bio.rusaer.com/archives/287
一,创建一个搜索表单
在网站中经常用到的就是表单,通过表单可以获得用户的信息,进行查询,进行添加,是一个很好的交互方式,下面就以最基本的查询表单来做示例。
1,首先,是在url.py文件中添加一个搜索视图。
(r’^search/$’,'sites.blog.views.search’)
2,其次,在视图模块sites.blog.views中些这个search视图:
def search(request):
query = request.GET.get(‘q’,”)
if query:
qset = ( Q(headline__contains=query)| Q(article__contains=query) )
results = Article.objects.filter(qset).distinct()
else:
results = []
return render_to_response("search.html",{‘results’: results, ‘query’: query})
如下图:
3,创建搜索视图模板,在模板文件夹新建search.html,内容如下
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"><html lang="en">
<head>
<title>Search{% if query %} Results{% endif %}</title>
</head>
<body>
<h1>Search</h1>
<form action="." method="GET">
<label for="q">Search: </label>
<input type="text" name="q" value="{{ query|escape }}">
# escape 过滤器来确保任何 可能的恶意的搜索文字被过滤出去,以保证不被插入到页面里。
<input type="submit" value="Search">
</form>
{% if query %}
<h2>Results for "{{ query|escape }}":</h2>
{% if results %}
<ul>
{% for article in results %}
<li>{{ article.headline|escape }}</li>
<li>{{ article.article|safe }}</l1>
{% endfor %}
</ul>
{% else %}
<p>No article found</p>
{% endif %}
{% endif %}
</body>
</html>
4,测试,结果如图:
搜索结果:
ok,搞定
二,创建一个回馈表单////由于新版本的form与老版本出现太多不同,所以此处到此为止。
一般网站都会有要求回馈,即用户通过表单发信息给网站管理者。
1,同样,往url.py文件中添加
(r’^contact/$’,'sites.blog.views.contact’)
2,定义表单,在django中表单的创建类似MODEL:使用python类来声明。
http://www.djangoproject.com/documentation/1.1.1/newforms/ 表单文档
为了管理方便,把它forms.py文件中,放到app目录blog下。
from django import newforms as forms
TOPIC_CHOICES = (
(‘general’, ‘General enquiry’),
(‘bug’, ‘Bug report’),
(‘suggestion’, ‘Suggestion’),
)
class ContactForm(forms.Form):
topic = forms.ChoiceField(choices=TOPIC_CHOICES)
message = forms.CharField(widget=forms.Textarea())
sender = forms.EmailField(required=False)
3,在views.py使用forms.py和定义contact
from forms import ContactForm
def contact(request):
form = ContactForm()
return render_to_response(‘contact.html’,{‘form’:form})
4,创建contact.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html lang="en">
<head>
<title>Contact us</title>
</head>
<body>
<h1>Contact us</h1>
<form action="." method="POST">
<table>
{{ form.as_table }}
#最有意思的一行是 {{ form.as_table }}。form 是ContactForm 的一个实例,我们通过 render_to_response 方法把它传递给模板。as_table 是form 的一个方法,它把 form 渲染成一系列的表格行(as_ul 和 as_p 也是起着相似的作用)。
</table>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
5,添加校验规则,刚开始什么规则都没添加。将原来的def contact(request)替换
def contact(request):
if request.method == ‘POST’:
form = ContactForm(request.POST)
else:
form = ContactForm()
return render_to_response(‘contact.html’, {‘form’: form})