Home Backend Development Python Tutorial 简单解析Django框架中的表单验证

简单解析Django框架中的表单验证

Jun 10, 2016 pm 03:09 PM
django form validation

我们的搜索示例仍然相当地简单,特别从数据验证方面来讲;我们仅仅只验证搜索关键值是否为空。 然后许多HTML表单包含着比检测值是否为空更为复杂的验证。 我们都有在网站上见过类似以下的错误提示信息:

  •     请输入一个有效的email地址, foo' 并不是一个有效的e-mail地址。
  •     请输入5位数的U.S 邮政编码, 123并非是一个有效的邮政编码。
  •     请输入YYYY-MM-DD格式的日期。
  •     请输入8位数以上并至少包含一个数字的密码。

关于JavaScript验证

可以使用Javascript在客户端浏览器里对数据进行验证,这些知识已超出本书范围。 要注意: 即使在客户端已经做了验证,但是服务器端仍必须再验证一次。 因为有些用户会将JavaScript关闭掉,并且还有一些怀有恶意的用户会尝试提交非法的数据来探测是否有可以攻击的机会。

除了在服务器端对用户提交的数据进行验证(例如在视图里验证),我们没有其他办法。 JavaScript验证可以看作是额外的功能,但不能作为唯一的验证功能。

我们来调整一下search()视图,让她能够验证搜索关键词是否小于或等于20个字符。 (为来让例子更为显著,我们假设如果关键词超过20个字符将导致查询十分缓慢)。那么该如何实现呢? 最简单的方式就是将逻辑处理直接嵌入到视图里,就像这样:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

def search(request):

  error = False

  if 'q' in request.GET:

    q = request.GET['q']

    if not q:

      error = True

    **elif len(q) > 20:**

      **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})

Copy after login

现在,如果尝试着提交一个超过20个字符的搜索关键词,系统不会执行搜索操作,而是显示一条错误提示信息。 但是,search_form.html里的这条提示信息是:”Please submit a search term.”,这显然是错误的, 所以我们需要更精确的提示信息:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<html>

<head>

  <title>Search</title>

</head>

<body>

  {% if error %}

    <p style="color: red;">Please submit a search term 20 characters or shorter.</p>

  {% endif %}

  <form action="/search/" method="get">

    <input type="text" name="q">

    <input type="submit" value="Search">

  </form>

</body>

</html>

Copy after login

但像这样修改之后仍有一些问题。 我们包含万象的提示信息很容易使人产生困惑: 提交一个空表单怎么会出现一个关于20个字符限制的提示? 所以,提示信息必须是详细的,明确的,不会产生疑议。

问题的实质在于我们只使用来一个布尔类型的变量来检测是否出错,而不是使用一个列表来记录相应的错误信息。 我们需要做如下的调整:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

def search(request):

  **errors = []**

  if 'q' in request.GET:

    q = request.GET['q']

    if not q:

      **errors.append('Enter a search term.')**

    elif len(q) > 20:

      **errors.append('Please enter at most 20 characters.')**

    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',

    {**'errors': errors** })

Copy after login

接着,我们要修改一下search_form.html模板,现在需要显示一个errors列表而不是一个布尔判断。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<html>

<head>

  <title>Search</title>

</head>

<body>

  **{% if errors %}**

    **<ul>**

      **{% for error in errors %}**

      **<li>{{ error }}</li>**

      **{% endfor %}**

    **</ul>**

  **{% endif %}**

  <form action="/search/" method="get">

    <input type="text" name="q">

    <input type="submit" value="Search">

  </form>

</body>

</html>

Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to check django version How to check django version Dec 01, 2023 pm 02:25 PM

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 vs. Flask: A comparative analysis of Python web frameworks Django vs. Flask: A comparative analysis of Python web frameworks Jan 19, 2024 am 08:36 AM

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 Framework Pros and Cons: Everything You Need to Know Django Framework Pros and Cons: Everything You Need to Know Jan 19, 2024 am 09:09 AM

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 django version How to check django version Nov 30, 2023 pm 03:08 PM

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.

What is the difference between django versions? What is the difference between django versions? Nov 20, 2023 pm 04:33 PM

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 upgrade Django version: steps and considerations How to upgrade Django version: steps and considerations Jan 19, 2024 am 10:16 AM

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

Is django front-end or back-end? Is django front-end or back-end? Nov 21, 2023 pm 02:36 PM

django is the backend. Details: Although Django is primarily a backend framework, it is closely related to front-end development. Through features such as Django's template engine, static file management, and RESTful API, front-end developers can collaborate with back-end developers to build powerful, scalable web applications.

How to handle form validation using middleware in Laravel How to handle form validation using middleware in Laravel Nov 02, 2023 pm 03:57 PM

How to use middleware to handle form validation in Laravel, specific code examples are required Introduction: Form validation is a very common task in Laravel. In order to ensure the validity and security of the data entered by users, we usually verify the data submitted in the form. Laravel provides a convenient form validation function and also supports the use of middleware to handle form validation. This article will introduce in detail how to use middleware to handle form validation in Laravel and provide specific code examples.

See all articles