改进Django中的表单的简单方法
首先,search()视图对于空字符串的处理相当薄弱——仅显示一条”Please submit a search term.”的提示信息。 若用户要重新填写表单必须自行点击“后退”按钮, 这种做法既糟糕又不专业。如果在现实的案例中,我们这样子编写,那么Django的优势将荡然无存。
在检测到空字符串时更好的解决方法是重新显示表单,并在表单上面给出错误提示以便用户立刻重新填写。 最简单的实现方法既是添加else分句重新显示表单,代码如下:
from django.http import HttpResponse from django.shortcuts import render_to_response from mysite.books.models import Book 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__icontains=q) return render_to_response('search_results.html', {'books': books, 'query': q}) else: **return render_to_response('search_form.html', {'error': True})**
(注意,将search_form()视图也包含进来以便查看)
这段代码里,我们改进来search()视图:在字符串为空时重新显示search_form.html。 并且给这个模板传递了一个变量error,记录着错误提示信息。 现在我们编辑一下search_form.html,检测变量error:
<html> <head> <title>Search</title> </head> <body> **{% if error %}** **<p style="color: red;">Please submit a search term.</p>** **{% endif %}** <form action="/search/" method="get"> <input type="text" name="q"> <input type="submit" value="Search"> </form> </body> </html>
我们修改了search_form()视图所使用的模板,因为search_form()视图没有传递error变量,所以在条用search_form视图时不会显示错误信息。
通过上面的一些修改,现在程序变的好多了,但是现在出现一个问题: 是否有必要专门编写search_form()来显示表单? 按实际情况来说,当一个请求发送至/search/(未包含GET的数据)后将会显示一个空的表单(带有错误信息)。 所以,只要我们改变search()视图:当用户访问/search/并未提交任何数据时就隐藏错误信息,这样就移去search_form()视图以及对应的URLpattern。
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})
在改进后的视图中,若用户访问/search/并且没有带有GET数据,那么他将看到一个没有错误信息的表单; 如果用户提交了一个空表单,那么它将看到错误提示信息,还有表单; 最后,若用户提交了一个非空的值,那么他将看到搜索结果。
最后,我们再稍微改进一下这个表单,去掉冗余的部分。 既然已经将两个视图与URLs合并起来,/search/视图管理着表单的显示以及结果的显示,那么在search_form.html里表单的action值就没有必要硬编码的指定URL。 原先的代码是这样:
<form action="/search/" method="get">
现在改成这样:
<form action="" method="get">
action=”“意味着表单将提交给与当前页面相同的URL。 这样修改之后,如果search()视图不指向其它页面的话,你将不必再修改action。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Steps to check the Django version: 1. Open a terminal or command prompt window; 2. Make sure Django has been installed. If Django is not installed, you can use the package management tool to install it and enter the pip install django command; 3. After the installation is complete , you can use python -m django --version to check the Django version.

Django and Flask are both leaders in Python Web frameworks, and they both have their own advantages and applicable scenarios. This article will conduct a comparative analysis of these two frameworks and provide specific code examples. Development Introduction Django is a full-featured Web framework, its main purpose is to quickly develop complex Web applications. Django provides many built-in functions, such as ORM (Object Relational Mapping), forms, authentication, management backend, etc. These features allow Django to handle large

Django is a complete development framework that covers all aspects of the web development life cycle. Currently, this framework is one of the most popular web frameworks worldwide. If you plan to use Django to build your own web applications, then you need to understand the advantages and disadvantages of the Django framework. Here's everything you need to know, including specific code examples. Django advantages: 1. Rapid development-Djang can quickly develop web applications. It provides a rich library and internal

How to check the django version: 1. To check through the command line, enter the "python -m django --version" command in the terminal or command line window; 2. To check in the Python interactive environment, enter "import django print(django. get_version())" code; 3. Check the settings file of the Django project and find a list named INSTALLED_APPS, which contains installed application information.

How to use JavaScript to realize the automatic prompt function of the input box content of the form? Introduction: The automatic prompt function of the form input box content is very common in web applications. It can help users quickly enter the correct content. This article will introduce how to use JavaScript to achieve this function and provide specific code examples. Create the HTML structure First, we need to create an HTML structure that contains the input box and the auto-suggestion list. You can use the following code: <!DOCTYP

The differences are: 1. Django 1.x series: This is an early version of Django, including versions 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8 and 1.9. These versions mainly provide basic web development functions; 2. Django 2.x series: This is the mid-term version of Django, including 2.0, 2.1, 2.2 and other versions; 3. Django 3.x series: This is the latest version series of Django. Including versions 3.0, 3, etc.

How to use JavaScript to implement real-time verification of the input box content of a form? In many web applications, forms are the most common way of interaction between users and the system. However, the content entered by the user often needs to be validated to ensure the accuracy and completeness of the data. In this article, we will learn how to use JavaScript to implement real-time verification of the content of the form's input box and provide specific code examples. Creating the form First we need to create a simple table in HTML

How to upgrade Django version: steps and considerations, specific code examples required Introduction: Django is a powerful Python Web framework that is continuously updated and upgraded to provide better performance and more features. However, for developers using older versions of Django, upgrading Django may face some challenges. This article will introduce the steps and precautions on how to upgrade the Django version, and provide specific code examples. 1. Back up project files before upgrading Djan
