一、Django如何处理浏览器来的数据
首先来做一个搜索页面,在templates中添加一个页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Search{% if query %} Result {% endif %}</title>
</head>
<body>
<h1>Search</h1>
<form action="." method="get">
<label for="q">Search:</label>
<input type="text" name="q" value="{{ query|escape}}">
<input type="submit" value="Search">
</form>
{% if query %}
<h2>Result for "{{ query | escape }}":</h2>
{% if results %}
<ul>
{% for book in results %}
<li>{{ book|escape }}</li>
{% endfor %}
</ul>
{% else %}
<p>No Books Found</p>
{% endif %}
{% endif %}
</body>
</html>
这里需要注意几个地方:
1、query = request.GET.get('q','') ---->寻找名为q的GET参数,而且如果参数没有提交,返回一个空的字符串
2、Q对象在这个例子用于建立复杂的查询,搜索匹配查询的任何数据。技术上Q对象包含QuerySet
3、为了防止XSS攻击,在所有使用query和book的地方,我们通过escape过滤器来确保任何可能的恶意的搜索文字被过滤出去,以保证不被插入到页面里
def search(request):
query = request.GET.get('q','')
if query:
qset = (
Q(title__icontains=query) |
Q(authors__first_name__icontains=query)
# Q(authors__last_name__icontains=query)
)
results = Book.objects.filter(qset).distinct()
else:
results = []
return render_to_response('search.html',{
"results":results,
"query":query
})
最后配置url
url('search/',search),
然后启动web服务试一下。
可以使用(当然,也可能会报错,我做的时候报错过,通过网页的提示自己调试一下就可以了)。
现在需要给网站里面加一个用户反馈页面:
我们在books文件夹下添加一个form.py文件
from django import 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(),initial="Replace with your feedback")
sender = forms.EmailField(required=False)
在view.py中添加代码:
@csrf_protect
def contact(request):
if request.method == 'post':
form = ContactForm(request.POST)
if form.is_valid():
topic = form.cleaned_data['topic']
message = form.cleaned_data['message']
sender = form.cleaned_data.get('sender','111.com.cn')
send_mail(
'Feedback from your site,topic:%s'%topic,
message,sender,
['1111@s1ft.com.cn']
)
return HttpResponseRedirect('/contact/thanks')
else:
form = ContactForm()
return render(request,'contact.html',{'form':form})
使用csrf_project注解需要引入:
from django.views.decorators.csrf import csrf_protect
url中配置:
url('contact/',contact)
再写contact页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{% block title %} {% endblock %}</title>
</head>
<body>
<h1>Contact us</h1>
<form action="." method="post">{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
启动服务,访问一下,长这个样子: