django:表单(1)

通常,表单开发分为两个部分: 前端HTML页面用户接口和后台view函数对所提交数据的处理过程

from django.shortcuts import render_to_response
from django.http import HttpResponse
from books.models import Book


# Create your views here.    表单
def search_form(request):
    return render_to_response('search_form.html')
def search(request):#表单的链接
    errors = []
    error = False
    if 'q' in request.GET:
    #检查q是否存在request.GET之外
        q = request.GET['q']
        #验证是否为空
        if not q:
            errors.append('Enter a search term.')
        #验证是否超过20个字符
        elif len(q)>20:
            errors.append('Please enter at most 20 characters')
        else:
            books = Book.objects.filter(title__icontains=q)
            #获取数据库中标题包含q的书籍,icontains是一个查询关键字
            return render_to_response('search_results.html',
                    {'books':books,'query':q})
    return render_to_response('search_form.html',{'errors':errors})
        #当字符串为空显示search_form.html,并且传递一个变量error

猜你喜欢

转载自blog.csdn.net/z13405546523/article/details/80057973
今日推荐