设为首页 加入收藏

TOP

Django学习笔记(五)―― 表单(一)
2015-07-20 18:06:46 来源: 作者: 【 】 浏览:30
Tags:Django 学习 笔记 表单

?

1. HttpRequest对象的信息

?

request.path 除域名以外的请求路径,斜杠开头 “/hello/”

request.get_host() 主机名 “127.0.0.1:8000” or “www.xxxx.com”

request.get_full_path() 请求路径,可能包含查询字符串 “/hello/?print=true”

request.is_secure() 是否通过Https访问 是为True,否为False

request.META 一个字典,包含本次Http请求的Header信息 例如 REMOTE_ADDR 表示客户端ip,

HTTP_USER_AGENT表示用户浏览器user-agent字符串

HTTP_REFERER表示进站前连接网页

request.POST 一个类字典对象保存html中

标签提交的内容

?

request.GET 一个类字典对象保存html中标签提交的内容或者URL中的查询字符串

?

例子:显示request.META 中的所有信息

在view.py中加入下面代码。并在urls.py加上对应的URLpattern

?

def test(request):
    values = request.META.items()
    values.sort()
    html = []
    for k,v in values:
        html.append('%s%s' %  (k,v))
    return HttpResponse('%s
' % ' '.join(html))

?

2. 一个简单的表单处理

?

在templates中创建search_form.html模板:

?

 
 
{% if error %}

Please submit a search term.

{% endif %}

?

?

其中action='' 表示表单将提交给与当前页面相同的URL

?

?

再添加search_results.html

?

?

 
 

You searched for: {{ query }}

{% if books %}

Found {{ books|length }} book{{ books|pluralize }}.

  • {% for book in books %}
  • {{ book.title }}
  • {% endfor %}
{% else %}

No books matched your search criteria.

{% endif %}

?

在view.py中添加:

?

def search(request):
    error = False
    if 'q' in request.GET:
        q = request.GET['q']
        if not q:
            error = True
        else:
            books = Book.objects.filter(title__icontains=q)
            return render_to_response('search_results.html',
                    {'books':books,'query':q})
    return render_to_response('search_form.html',
            {'error':error})
    

?

?

?

其中Book.objects.filter(title__icontains=q) 是用来获取数据库中标题包含q的书籍。icontains是一个查询关键字。

?

在urls.py 中添加

?

  (r'search/$',search),

?

?

然后在浏览器输入 http://127.0.0.1:8000/search/ 可以看到一个简单的搜索界面。

?

3. 简单的验证

?

可以用Javascript在客户端浏览器进行验证,但可能有些人会将java script关闭,并且还有一些怀有恶意的用户会尝试提交非法的数据来探测是否有可以攻击的机会。所以除了用java script在客户端浏览器进行验证外,还需要在服务器验证一次。上面的代码,只对 输入为空做了验证。下面添加一个验证搜索关键字是否小于20个字符的验证。

?

例子:

修改view.py

?

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)
            return render_to_response('search_results.html',
                    {'books':books,'query':q})
    return render_to_response('search_form.html',
            {'errors':errors})


?

修改 search_form.html :

?

 
  {% if errors %} {% for error in errors%} 
 

{{ error }}

{% endfor %} {% endif %}
?

?

4. 编写Contact表单

?

?

一个较为复杂的例子:这个表单包括用户提交的反馈信息,一个可以选择填不填的e-mail地址。

?

view.py 中添加:

?

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/')
    return render_to_response('contact_form.html', {
        'errors': errors,
        'subject': request.POST.get('subject', ''),
        'message': request.POST.get('message', ''),
        'email': request.POST.get('email', ''),
    },context_instance=RequestContext(request))

?

?

用POST不用GET,因为这个表单会有一个服务器端的操作:send_mail。

首页 上一页 1 2 3 下一页 尾页 1/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇POJ 1915: Knight Moves 下一篇UVALive 6469 Deranged Exams (排..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: