Django获取表单数据并从数据库查询

来源:互联网 发布:人事软件 考勤 编辑:程序博客网 时间:2024/05/22 13:31

views.py从request.GET中获取需查找的关键字,然后从数据库中查找

from django.http import HttpResponsefrom django.shortcuts import render_to_responsefrom mysite.books.models import Bookdef search(request):    if 'q' in request.GET and request.GET['q']:  #获得用户输入值        q = request.GET['q']        books = Book.objects.filter(title__icontains=q) #调用model文件中的Book类方法处理后返回结果        return render_to_response('search_results.html', #渲染输出模板            {'books': books, 'query': q})    else:        return HttpResponse('Please submit a search term.')

从html中获取搜索关键字

<html><head>    <title>Search</title></head><body>    <form action="/search/" method="get">        <input type="text" name="q">        <input type="submit" value="Search">    </form></body></html>

其中action .表示对当前文件进行操作
method 表示提交的方法是GET还是POST

0 0
原创粉丝点击