Python笔记19(Django中form的用法)

一、内容回顾

书籍的增删改例子对之前的内容进行一下总结:

from django.db import models

# Create your models here.


class Publisher(models.Model):
    name = models.CharField(max_length=32, unique=True, verbose_name="出版社名称")
    address = models.TextField(verbose_name="出版社地址")

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "出版社"
        verbose_name_plural = verbose_name


class Author(models.Model):
    name = models.CharField(max_length=12)
    gender = models.SmallIntegerField(
        choices=((0, ""), (1, ""), (2, "保密")),
        default=2
    )
    age = models.IntegerField()

    def __str__(self):
        return self.name


class Book(models.Model):
    title = models.CharField(max_length=32, unique=True)
    # auto_now_add:创建时间  auto_add:修改时间
    publish_date = models.DateField(auto_now_add=True)
    phone = models.CharField(max_length=11, unique=True, null=True, blank=True)
    publisher = models.ForeignKey(to="Publisher", on_delete=models.CASCADE)
    authors = models.ManyToManyField(to="Author")

    def __str__(self):
        return self.title
models.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),

    url(r'^book_list/$', views.book_list),
    url(r'^add_book/$', views.add_book),
    url(r'^edit_book/(\d+)/$', views.edit_book),  # edit_book(request, id)
]
urls.py
from django.shortcuts import render, redirect
from app01 import models
from django import forms
# Create your views here.


# 自定义一个form类
class BookForm(forms.Form):
    title = forms.CharField(max_length=12)
    publish_date = forms.DateField()
    phone = forms.CharField(max_length=11)
    publisher = forms.ChoiceField()
    authors = forms.ChoiceField()


def book_list(request):
    data = models.Book.objects.all()
    # return render(request, "book_list.html", {"data": data})
    # locals()以字典的形式把当前作用域的变量表示出来
    return render(request, "book_list.html", locals())


def add_book(request):
    if request.method == "POST":
        # 从用户提交过来的数据中取数据
        title = request.POST.get("title")
        publish_date = request.POST.get("publish_date")
        phone = request.POST.get("phone")
        publisher = request.POST.get("publisher")
        authors = request.POST.getlist("authors")

        # 去数据库创建书籍
        book_obj = models.Book.objects.create(
            title=title,
            publish_date=publish_date,
            publisher_id=publisher,
        )
        book_obj.authors.add(*authors)  # add接收一个一个的值,直接传列表不行需要打散
        return redirect("/book_list/")

    publisher_list = models.Publisher.objects.all()
    author_list = models.Author.objects.all()
    return render(request, "add_book.html", locals())


def edit_book(request, pk):
    book_obj = models.Book.objects.filter(id=pk).first()
    if request.method == "POST":
        # 从用户提交过来的数据中取数据
        title = request.POST.get("title")
        publish_date = request.POST.get("publish_date")
        publisher = request.POST.get("publisher")
        authors = request.POST.getlist("authors")
        # 去数据库更新对应的书籍
        book_obj.title = title
        book_obj.publish_date = publish_date
        book_obj.publisher_id = publisher
        book_obj.save()
        book_obj.authors.set(authors)  # 让ORM去更新第三张关系表
        return redirect("/book_list/")

    publisher_list = models.Publisher.objects.all()
    author_list = models.Author.objects.all()
    return render(request, "edit_book.html", locals())
views.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加书籍</title>
</head>
<body>

<h1>添加书籍</h1>
<form action="" method="post">
    {% csrf_token %}
    <p>书名:
        <input type="text" name="title">
    </p>
    <p>出版日期:
        <input type="date" name="publish_date">
    </p>
    <p>
        出版社:
        <select name="publisher">
            {% for publisher in publisher_list %}
                <option value="{{ publisher.id }}">{{ publisher.name }}</option>
            {% endfor %}
        </select>
    </p>
    <p>作者:
        <select name="authors" multiple>
            {% for author in author_list %}
                <option value="{{ author.id }}">{{ author.name }}</option>
            {% endfor %}
        </select>
    </p>
    <input type="submit">
</form>
</body>
</html>
add_book.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<a href="/add_book/">添加书籍</a>
<table border="1">
    <tbody>
    {% for book in data %}
        <tr>
            <td>{{ forloop.counter }}</td>
            <td>{{ book.id }}</td>
            <td>{{ book.title }}</td>
            <td>{{ book.publish_date }}</td>
            <td>{{ book.publisher }}</td>
            <td>{{ book.authors.all }}</td>
            <td>
                <a href="">删除</a>
                <a href="/edit_book/{{ book.id }}/">编辑</a>
            </td>
        </tr>
    {% endfor %}

    </tbody>
</table>
</body>
</html>
book_list.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编辑书籍</title>
</head>
<body>

<h1>编辑书籍</h1>
<form action="" method="post">
    {% csrf_token %}
    <p>书名:
        <input type="text" name="title" value="{{ book_obj.title }}">
    </p>
    <p>出版日期:
        <input type="date" name="publish_date" value="{{ book_obj.publish_date|date:'Y-m-d' }}">
    </p>
    <p>
        出版社:
        <select name="publisher">
            {% for publisher in publisher_list %}
                {% if publisher.id == book_obj.publisher_id %}
                    <option selected value="{{ publisher.id }}">{{ publisher.name }}</option>
                {% else %}
                    <option value="{{ publisher.id }}">{{ publisher.name }}</option>
                {% endif %}
            {% endfor %}
        </select>
    </p>
    <p>作者:
        <select name="authors" multiple>
            {% for author in author_list %}
                {% if author in book_obj.authors.all %}
                    <option selected value="{{ author.id }}">{{ author.name }}</option>
                {% else %}
                    <option value="{{ author.id }}">{{ author.name }}</option>
                {% endif %}
            {% endfor %}
        </select>
    </p>
    <input type="submit">
</form>
</body>
</html>
edit_book.html

二、Django form表单

1、form介绍

我们之前在HTML页面中利用form表单向后端提交数据时,都会写一些获取用户输入的标签并且用form标签把它们包起来。

与此同时我们在好多场景下都需要对用户的输入做校验,比如校验用户是否输入,输入的长度和格式等正不正确。如果用户输入的内容有错误就需要在页面上相应的位置显示对应的错误信息.。

Django form组件就实现了上面所述的功能。

总结一下,其实form组件的主要功能如下:

  • 生成页面可用的HTML标签
  • 对用户提交的数据进行校验
  • 保留上次输入内容

猜你喜欢

转载自www.cnblogs.com/xingye-mdd/p/9557827.html
今日推荐