HttpRequest----request
常用的
request.path | 除域名以外的请求路径,以正斜杠开头 | "/hello/" |
request.get_host() | 主机名(比如,通常所说的域名) | "127.0.0.1:8000" or"www.example.com" |
request.get_full_path() | 请求路径,可能包含查询字符串 | "/hello/?print=true" |
request.is_secure() | 如果通过HTTPS访问,则此方法返回True, 否则返回False | |
request.META | 是一个Python字典,包含了所有本次HTTP请求的Header信息 | 很多东西 |
HTTP_REFERER | 进站前链接网页 | |
HTTP_USER_AGENT | "Mozilla/5.0 (X11; U; Linux i686; fr-FR; rv:1.8.1.17) Gecko/20080829 Firefox/2.0.0.17" | |
REMOTE_ADDR | "12.345.67.89,23.456.78.90" | |
request.GET | 类字典对象,POST数据是来自HTML中的〈form〉标签提交的 | |
request.POST | 类字典对象,GET数据可能来自〈form〉提交也可能是URL中的查询字符串(例如/search/?q=django) |
三种常见返回
from django.http import HttpResponse
def hello(request):
return HttpResponse("Hello world")
from django.shortcuts import render_to_response
def search_form(request):
return render_to_response('search_form.html')
from django.http import HttpResponseRedirect
return HttpResponseRedirect('/contact/thanks/')
典型的数据交互
一个get例子
def search(request):
errors = [] # 收集错误信息交给前端(简单处理后显示)
if 'q' in request.GET:
q = request.GET['q']
if not q:
errors.append('Enter a search term.')
elif len(q) > 20:
errors.append('Please enter at most 20 characters.')
else:
books = Book.objects.filter(title__icontains=q)
# 数据库的操作见 icontains(大小写无关的LIKE)
return render_to_response('search_results.html',{'books': books, 'query': q})
return render_to_response('search_form.html',{'errors': errors })
# 若用户刷新一个包含POST表单的页面,那么请求将会重新发送造成重复。重定向喽
# search_form.html
<html>
<head>
<title>Search</title>
</head>
<body>
{% if errors %} # 显示错误<p ><p>会更漂亮点
<ul>
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
<form action="/search/" method="get">
<input type="text" name="q"> # 后端通过 q 拿值
<input type="submit" value="Search">
</form>
</body>
</html>
# search_results.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>You searched for: <strong>{{ query }}</strong></p>
{% if books %}
<p>Found {{ books|length }} book{{ books|pluralize }}.</p>
# 模板的过滤器 length 返回变量的长度 pluralize 单词的复数形式,如列表字符串个数大于1,返回s,否则返回空串
<ul>
{% for book in books %}
<li>{{ book.title }}</li>
{% endfor %}
</ul>
{% else %}
<p>No books matched your search criteria.</p>
{% endif %}
</body>
</html>
一个post的例子
# views.py
from django.core.mail import send_mail
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
def contact(request):
errors = []
if request.method == 'POST':
if not request.POST.get('subject', ''):
errors.append('Enter a subject.')
if not request.POST.get('message', ''):
errors.append('Enter a message.')
if request.POST.get('email') and '@' not in request.POST['email']:
errors.append('Enter a valid e-mail address.')
if not errors:
send_mail( # 四个必选参数: 主题,正文,寄信人和收件人列表。
request.POST['subject'],
request.POST['message'],
request.POST.get('email', 'noreply@example.com'),
['siteowner@example.com'],
)
return HttpResponseRedirect('/contact/thanks/')
# 若用户刷新一个包含POST表单的页面,那么请求将会重新发送造成重复。
# 所以重定向,应每次都给成功的POST请求做重定向。
return render(request, 'contact_form.html', {
'errors': errors,
'subject': request.POST.get('subject', ''),
'message': request.POST.get('message', ''),
'email': request.POST.get('email', ''),
})
# 验证失败后,返回客户端的表单中各字段最好是填有原来提交的数据
# contact_form.html
<html>
<head>
<title>Contact us</title>
</head>
<body>
<h2>Contact us</h2>
{% if errors %}
<ul>
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
<form action="/contact/" method="post">
<p>Subject: <input type="text" name="subject" value="{{ subject }}"></p>
<p>Your e-mail (optional): <input type="text" name="email" value="{{ email }}"></p>
<p>Message: <textarea name="message" rows="10" cols="50"> {{ message }} </textarea></p>
<input type="submit" value="Submit">
</form>
</body>
</html>
详解form表单
有点类似模型,定义各个字段的类型
from django import forms
class ContactForm(forms.Form):
subject = forms.CharField()
email = forms.EmailField(required=False)
message = forms.CharField()
form将数据格式化成html的形式
>>> from contact.forms import ContactForm
>>> f = ContactForm()
>>> print f
<tr><th><label for="id_subject">Subject:</label></th><td><input type="text" name="subject" id="id_subject" /></td></tr>
<tr><th><label for="id_email">Email:</label></th><td><input type="text" name="email" id="id_email" /></td></tr>
<tr><th><label for="id_message">Message:</label></th><td><input type="text" name="message" id="id_message" /></td></tr>
默认是tr th 可以换成下面两种形式
>>> print f.as_ul()
<li><label for="id_subject">Subject:</label> <input type="text" name="subject" id="id_subject" /></li>
>>> print f.as_p()
<p><label for="id_subject">Subject:</label> <input type="text" name="subject" id="id_subject" /></p>
对每个字段取值
>>> print f['subject']
<input type="text" name="subject" id="id_subject" />
>>> print f['message']
<input type="text" name="message" id="id_message" />
创建时赋值(字典形式)
>>> f = ContactForm({'subject': 'Hello', 'email': 'adrian@example.com', 'message': 'Nice site!'})
判断
>>> f.is_bound 一旦你对一个Form实体赋值,你就得到了一个绑定form
True
>>> f.is_valid() 判断是否合法,默认都是必需填参数
True
errors
每一个邦定Form实体都有一个errors属性,它为你提供了一个字段与错误消息相映射的字典表。
>>> f = ContactForm({'subject': 'Hello', 'message': ''})
>>> f.errors # 不合法的赋值的字段,会成为字典里的items
{'message': [u'This field is required.']}
>>> f['subject'].errors
[]
清理数据
>>> f = ContactForm({subject': Hello, email: adrian@example.com, message: Nice site!})
>>> f.is_valid() # 如果一个Form实体的数据是合法的,它就会有一个可用的cleaned_data属性。
True
>>> f.cleaned_data # 这是一个包含干净的提交数据的字典。
{message': uNice site!, email: uadrian@example.com, subject: uHello}
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。