首页 > 代码库 > django表单
django表单
视图函数 views.py
# -*-coding:utf-8-*-from django.http import HttpResponse, Http404from django.template.loader import get_templatefrom django.template import Template,Contextfrom django.shortcuts import render_to_responsefrom books.models import Bookdef request_meta(request): item_list = request.META.items() item_list.sort() return render_to_response(‘request_meta.html‘,{‘item_list‘: item_list})def request_meta_2(request): item_list = request.META.items() item_list.sort() t = get_template(‘request_meta.html‘) cxt = Context({‘item_list‘: item_list}) return HttpResponse(t.render(cxt))def search_form(request): return render_to_response(‘search_form.html‘)def search(request): if ‘q‘ in request.GET and request.GET[‘q‘]: #检查是否为空 q = request.GET[‘q‘] books = Book.objects.filter(title__contains=q) return render_to_response(‘search_results.html‘,{‘books‘: books, ‘query‘: q}) else: return HttpResponse(‘Please submit a search term.‘)
模板文件:request_meta.html,search_form.html,search_result.html
<html><head> <title>this is a django app</title></head><body> <table> {% for key,value in item_list %} {% if forloop.first %} <tr><td>I am first row</td><td>{{ key }}</td><td>{{ value }}</td></tr> {% endif %} {% comment %} {% if not forloop.first %} {% if not forloop.last %} <tr><td>{{ forloop.counter }}</td><td>{{ key }}</td><td>{{ value }}</td></tr> {% endif %} {% endif %} {% endcomment %} {% if not forloop.first or not forloop.last %} <tr><td>{{ forloop.counter }}</td><td>{{ key }}</td><td>{{ value }}</td></tr> {% endif %} {% if forloop.last %} <tr><td>I am last row</td><td>{{ key }}</td><td>{{ value }}</td></tr> {% endif %} {% endfor %} </table></body></html>
<!DOCTYPE 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>
<!DOCTYPE html><html><head> <title>Search</title></head><body> {# pluralize在合适的时候显示s #} Query String is: {{ query }} {% if books %} <p>Found {{ books|length }} book{{ book|pluralize }}</p> {% for book in books %} <li>{{ book.title}}</li> {% endfor %} {% else %} <p>No books matched your search criteria.</p> {% endif %}</body></html>
备注:启用django模板系统许要在settings.py中进行模板配置
TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don‘t forget to use absolute paths, not relative paths. os.path.join(os.path.dirname(__file__), ‘templates‘).replace(‘\\‘, ‘/‘),)
django表单
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。