首页 > 代码库 > 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表单