Django进阶三

一、Django Admin的简单用法

  1.   创建管理员账号

    python manage.py createsuperuser
  2.   在admin注册我们的表(/project/app01/admin.py)

    from app01 import models
    admin.site.register(models.类名)
    
    示例:
    from django.contrib import admin
    from app01 import models
    # Register your models here
    admin.site.register(models.Author)
    admin.site.register(models.Publisher)
    admin.site.register(models.Book)
  3.   其他配置项

    1. admin页面显示中文(settings.py)
        settings.py中修改LANGUAGE_CODE = ‘zh-hans‘
    2. 表名显示中文(models.py)
        类下面写如下配置项
            class Meta:
                verbose_name = "出版社"
                verbose_name_plural = verbose_name
    3. 字段显示中文(models.py)
        address = models.TextField(verbose_name="出版社地址")
  4.   代码示例

    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, verbose_name="作者名称")
        gender = models.SmallIntegerField(
            choices=((0, "女"), (1, "男"), (2, "保密")),
            default=2,
            verbose_name="性别"
        )
        age = models.IntegerField(verbose_name="年龄")
    
        def __str__(self):
            return self.name
    
        class Meta:
            verbose_name = "作者管理"
            verbose_name_plural = verbose_name
    
    class Book(models.Model):
        title = models.CharField(max_length=32, unique=True, verbose_name="书籍名称")
        # auto_now_add:创建时间  auto_add:修改时间
        publish_date = models.DateField(auto_now_add=True, verbose_name="出版时间")
        phone = models.CharField(max_length=11, unique=True, null=True, blank=True, verbose_name="手机号")
        publisher = models.ForeignKey(to="Publisher", on_delete=models.CASCADE, verbose_name="出版社")
        authors = models.ManyToManyField(to="Author", verbose_name="作者")
    
        def __str__(self):
            return self.title
    
        class Meta:
            verbose_name = "书籍管理"
            verbose_name_plural = verbose_name

    代码示例

二、form和model form:https://www.cnblogs.com/liwenzhou/p/8747872.html

  1.   form

    1.   form的作用

      1. 生成HTML代码
      2. 帮我们做数据有效性的校验
      3. 保留上次输入内容,显示错误提示
    2.   代码示例
      1.   手写版本

        from django.db import models
        
        # Create your models here.
        
        class Book(models.Model):
        """
        书籍表
        """
        name = models.CharField(max_length=36, verbose_name="图书", unique=True)
        publisher = models.ForeignKey(to="Publisher", default=None, verbose_name="出版社")
        authors = models.ManyToManyField(to="Author", verbose_name="作者")
        create_time = models.DateField(auto_now_add=True, null=True)
        
        def __str__(self):
            return self.name
        
        class Meta:
            verbose_name = "图书管理"
            verbose_name_plural = verbose_name
        
        class Publisher(models.Model):
        """
        出版社表
        """
        name = models.CharField(max_length=36, verbose_name="出版社", unique=True)
        address = models.TextField(verbose_name="出版社地址")
        create_time = models.DateField(auto_now_add=True, null=True)
        
        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, verbose_name="作者")
        sex = models.SmallIntegerField(
            choices=((0, "女"), (1, "男"), (2, "保密")),
            default=2,
            verbose_name="性别"
        )
        age = models.IntegerField(verbose_name="年龄", null=True)
        create_time = models.DateField(auto_now_add=True, null=True)
        
        def __str__(self):
            return self.name
        
        class Meta:
            verbose_name = "作者管理"
            verbose_name_plural = verbose_name

        model.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),
        ]

        urls.py

        from django.shortcuts import render, redirect
        from app01 import models
        
        # Create your views here.
        
        def book_list(request):
            """
            书籍列表
            :param request:
            :return:
            """
            data = models.Book.objects.all()
            return render(request, "book_list.html", locals())
        
        def add_book(request):
            """
            添加书籍
            :param request:
            :return:
            """
        
            if request.method == "POST":
                book_name = request.POST.get("book_name")
                publisher_name = request.POST.get("publisher_name")
                author_name = request.POST.getlist("author_name")
                book_obj = models.Book.objects.create(name=book_name, publisher_id=publisher_name)
                book_obj.authors.add(*author_name)
                return redirect("/book_list/")
            authors = models.Author.objects.all()
            publishers = models.Publisher.objects.all()
            return render(request, "add_book.html", locals())
        
        def edit_book(request, book_id):
            """
            编辑书籍
            :param request:
            :return:
            """
            book_obj = models.Book.objects.filter(id=book_id).first()
            if request.method == "POST":
                book_name = request.POST.get("book_name")
                publisher_name = request.POST.get("publisher_name")
                author_name = request.POST.getlist("author_name")
                book_obj.name = book_name
                book_obj.publisher_id = publisher_name
                book_obj.save()
                book_obj.authors.set(author_name)
                return redirect("/book_list/")
        
            authors = models.Author.objects.all()
            publishers = models.Publisher.objects.all()

        views.py

        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>书籍列表</title>
            <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.min.css">
        </head>
        <body>
        <a href="/add_book/" class="btn btn-success">添加书籍</a>
        <table class="table">
            <thead>
            <tr>
                <td>#</td>
                <td>名称</td>
                <td>作者</td>
                <td>出版社</td>
                <td>操作</td>
            </tr>
            </thead>
            <tbody>
            {% for datum in data %}
                <tr>
                    <td>{{ forloop.counter }}</td>
                    <td>{{ datum.name }}</td>
                    <td>
                        {% for author in datum.authors.all %}
                            {% if forloop.last %}
                                {{ author.name }}
                            {% else %}
                                {{ author.name }},
                            {% endif %}
                        {% endfor %}
                    </td>
                    <td>{{ datum.publisher.name }}</td>
                    <td>
                        <a href="/edit_book/{{ datum.id }}/" class="btn btn-success">编辑</a>
                        <a href="" class="btn btn-warning">删除</a>
                    </td>
                </tr>
            {% endfor %}
        
            </tbody>
        </table>
        </body>
        </html>

        html-book_list.html

        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>添加书籍</title>
            <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.min.css">
        </head>
        <body>
        
        <form action="" method="post">
        {% csrf_token %}
            <div class="form-group">
                <label for="book_name">书籍名称</label>
                <input type="text" class="form-control" id="book_name" placeholder="书籍名称" name="book_name">
            </div>
            <div class="form-group">
            <label for="publisher_name">出版社</label>
                <select name="publisher_name" id="" class="form-control">
                    {% for publisher in publishers %}
                        <option value="{{ publisher.id }}">{{ publisher.name }}</option>
                    {% endfor %}
                </select>
            </div>
            <div class="form-group">
                <label for="author_name">作者</label>
                <select name="author_name" id="" class="form-control" multiple>
                    {% for author in authors %}
                        <option value="{{ author.id }}">{{ author.name }}</option>
                    {% endfor %}
                </select>
            </div>
            <button type="submit" class="btn btn-default">提交</button>
        </form>
        </body>
        </html>

        html-add_book.html

        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>编辑书籍</title>
            <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.min.css">
        </head>
        <body>
        
        <form action="" method="post">
            {% csrf_token %}
            <div class="form-group">
                <label for="book_name">书籍名称</label>
                <input type="text" class="form-control" id="book_name" value="{{ book_obj.name }}" name="book_name">
            </div>
            <div class="form-group">
                <label for="publisher_name">出版社</label>
                <select name="publisher_name" id="" class="form-control">
                    {% for publisher in publishers %}
                        {% if book_obj.publisher_id == publisher.id %}
                            <option value="{{ publisher.id }}" selected>{{ publisher.name }}</option>
                        {% else %}
                            <option value="{{ publisher.id }}">{{ publisher.name }}</option>
                        {% endif %}
                    {% endfor %}
                </select>
            </div>
            <div class="form-group">
                <label for="author_name">作者</label>
                <select name="author_name" id="" class="form-control" multiple>
                    {% for author in authors %}
                        {% if author in  book_obj.authors.all %}
                            <option value="{{ author.id }}" selected>{{ author.name }}</option>
                            {% else %}
                             <option value="{{ author.id }}">{{ author.name }}</option>
                        {% endif %}
                    {% endfor %}
                </select>
            </div>
            <button type="submit" class="btn btn-default">提交</button>
        </form>
        </body>
        </html>

        html-edit_book.html

      2.   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, verbose_name="作者名称")
            gender = models.SmallIntegerField(
                choices=((0, "女"), (1, "男"), (2, "保密")),
                default=2,
                verbose_name="性别"
            )
            age = models.IntegerField(verbose_name="年龄")
        
            def __str__(self):
                return self.name
        
            class Meta:
                verbose_name = "作者管理"
                verbose_name_plural = verbose_name
        
        class Book(models.Model):
            title = models.CharField(max_length=32, unique=True, verbose_name="书籍名称")
            # auto_now_add:创建时间  auto_add:修改时间
            publish_date = models.DateField(auto_now_add=True, verbose_name="出版时间")
            phone = models.CharField(max_length=11, unique=True, null=True, blank=True, verbose_name="手机号")
            publisher = models.ForeignKey(to="Publisher", on_delete=models.CASCADE, verbose_name="出版社")
            authors = models.ManyToManyField(to="Author", verbose_name="作者")
        
            def __str__(self):
                return self.title
        
            class Meta:
                verbose_name = "书籍管理"
                verbose_name_plural = verbose_name

        model.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, HttpResponse
        from app01 import models
        from django import forms
        from django.core.validators import RegexValidator
        from django.core.exceptions import ValidationError
        # Create your views here.
        
        # 自定义一个字段的校验规则函数
        def phone_validate(value):
            # 拿用户填写的手机号去数据库查找有没有
            is_exist = models.Book.objects.filter(phone=value)
            if is_exist:
                # 如果该手机号已经被使用就不能再注册
                raise ValidationError("该手机号已经被注册!")
            else:
                return value
        
        # 自定义一个form类
        class BookForm(forms.Form):
            title = forms.CharField(
                max_length=12,
                min_length=6,
                label="书名",
                # initial="书名的默认值",
                widget=forms.widgets.TextInput(attrs={"class": "form-control"})
            )
            publish_date = forms.DateField(
                label="出版日期",
                widget=forms.widgets.DateInput(attrs={"type": "date", "class": "form-control"})
            )
            phone = forms.CharField(
                max_length=11,
                # required=False,
                # validators=[RegexValidator(r‘^1[356789]\d{9}$‘, "手机号码格式不正确"), phone_validate],
                validators=[RegexValidator(r‘^1[356789]\d{9}$‘, "手机号码格式不正确")],
                widget=forms.widgets.TextInput(attrs={"class": "form-control"})
            )
            # publisher = forms.ChoiceField(
            #     # choices=models.Publisher.objects.values_list("id", "name"),
            #     widget=forms.widgets.Select()
            # )
            publisher = forms.ModelChoiceField(
                queryset=models.Publisher.objects.all(),
                widget=forms.widgets.Select(attrs={"class": "form-control"})
            )
            authors = forms.ModelMultipleChoiceField(
                queryset=models.Author.objects.all(),
                widget=forms.widgets.SelectMultiple(attrs={"class": "form-control"})
            )
        
            # 自定义一个局部钩子函数
            def clean_title(self):
                value = self.cleaned_data.get("title")
                # 判断有没有敏感词
                if "alex" in value:
                    raise ValidationError("alex已被河蟹...")
                else:
                    return value
        
            # 全局钩子函数
            def clean(self):
                # 可以从self.cleaned_data取到所有字段的数据
                # self.add_error("字段", "密码和确认密码不一致")
                pass
        
        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):
            form_obj = BookForm()
            if request.method == "POST":
                # 从用户提交过来的数据中取数据
                # 做校验
                form_obj = BookForm(request.POST)
                if form_obj.is_valid():  # 做数据有效性的校验
                    # 去数据库创建新的数据
                    print(form_obj.cleaned_data)
                    # 因为有多对多的字段,所以需要额外处理
                    authors = form_obj.cleaned_data.pop("authors")
                    # 创建新书籍对象
                    book_obj = models.Book.objects.create(**form_obj.cleaned_data)
                    # 将书籍对象和作者建立关联
                    book_obj.authors.add(*authors)
                    return redirect("/book_list/")
        
            return render(request, "add_book.html", locals())
        
        def edit_book(request, pk):
            book_obj = models.Book.objects.filter(id=pk).first()
            # book_dict = {
            #     "title": book_obj.title,
            #     "publish_date": book_obj.publish_date.strftime("%Y-%m-%d"),
            # }
            # 把ORM中一个对象 快速转换成 字典格式
            from django.forms import model_to_dict
            book_dict = model_to_dict(book_obj)
            book_dict["publish_date"] = book_obj.publish_date.strftime("%Y-%m-%d")
            print(book_dict)
            print("=" * 120)
            # form_obj = BookForm({"title": "书的默认值呀2", "publish_date": "2018-01-01"})
            form_obj = BookForm(book_dict)
            if request.method == "POST":
                # 从用户提交过来的数据中取数据
                form_obj = BookForm(request.POST)
                if form_obj.is_valid():
                    # 去数据库更新对应的书籍
                    book_obj.title = form_obj.cleaned_data.get("title")
                    book_obj.publish_date = form_obj.cleaned_data.get("publish_date")
                    book_obj.publisher_id = form_obj.cleaned_data.get("publisher")
                    book_obj.save()
                    book_obj.authors.set(form_obj.cleaned_data.get("authors"))  # 让ORM去更新第三张关系表
                    return redirect("/book_list/")
        
            return render(request, "edit_book.html", locals())

        views.py

        <!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>

        html-book_list.html

        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>添加书籍</title>
            <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">
        </head>
        <body>
        
        <div class="container">
            <div class="row">
                <div class="col-md-8 col-md-offset-2">
                    <h1>添加书籍</h1>
        
                    <form action="" method="post" novalidate autocomplete="off">
                        {% csrf_token %}
                        {% for field in form_obj %}
                            <div class="form-group">
                                <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                                {{ field }}
                                <p>{{ field.errors.0 }}</p>
                            </div>
                        {% endfor %}
                        <input type="submit" class="btn btn-success">
                    </form>
                </div>
            </div>
        </div>
        
        </body>
        </html>

        html-add_book.html

        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>编辑书籍</title>
            <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">
        </head>
        <body>
        
        <div class="container">
            <div class="row">
                <div class="col-md-8 col-md-offset-2">
                    <h1>编辑书籍</h1>
                    <form action="" method="post">
                        {% csrf_token %}
                        {% for field in form_obj %}
                            <div class="form-group">
                                <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                                {{ field }}
                                <p>{{ field.errors.0 }}</p>
                            </div>
                        {% endfor %}
                        <input type="submit" class="btn btn-success">
                    </form>
                </div>
            </div>
        </div>
        
        </body>
        </html>

        html

      3.   form组件校验数据有效性

        1. 内置的校验规则
            1. require=True    该字段必填
            2. max_length      该字段的最大长度
            3. min_length      该字段的最小长度
        2. 自定义校验规则
            1. phone的格式 利用内置的正则校验器
                from django.core.validators import RegexValidator
                validators=[RegexValidator(r‘^1[356789]\d{9}$‘, "手机号码格式不正确")],
        
            2. 手机号的唯一性校验
                validators=[RegexValidator(r‘^1[356789]\d{9}$‘, "手机号码格式不正确"), phone_validate],
        
                # 自定义一个字段的校验规则函数
                def phone_validate(value):
                    # 拿用户填写的手机号去数据库查找有没有
                    is_exist = models.Book.objects.filter(phone=value)
                    if is_exist:
                        # 如果该手机号已经被使用就不能再注册
                        raise ValidationError("该手机号已经被注册!")
                    else:
                        return value
        
                        3. 使用钩子函数做校验
                            1. 局部钩子(hook)
                                在form类内部定义一个 clean_字段名() 方法
                                # 自定义一个局部钩子函数
                                def clean_title(self):
                                    value = self.cleaned_data.get("title")
                                    # 判断有没有敏感词
                                    if "alex" in value:
                                        raise ValidationError("alex已被河蟹...")
                                    else:
                                        return value
        
            2. 全局钩子
                在form类内部定义一个 clean() 方法
                # 全局钩子函数
                def clean(self):
                    # 可以从self.cleaned_data取到所有字段的数据
                    # self.add_error("字段", "密码和确认密码不一致")
                    pass
      4.   form组合如何给html标签设置默认值

        1. 每一个字段设置默认值
            initial="默认值"
  1.   model form

    1. 必须继承forms.ModelForm
        class BookModelForm(forms.ModelForm):
    2. class Meta:
        class Meta:
            model = models.Book
            # fields = "__all__"  # model类里所有的字段都展示
            # fields = ["title", ]  # 指定展示某些字段
            exclude = ["title", ]  # 除了指定字段,其他字段都展示
            labels = {  # 设置label标签名
                "title": "书名",
                "phone": "手机号",
                "publisher": "出版社",
                "authors": "作者",
            }
            widgets = {  # 设置每个字段的插件信息
                "title": forms.widgets.TextInput(attrs={"class": "form-control"}),
                "phone": forms.widgets.TextInput(attrs={"class": "form-control"}),
                "publisher": forms.widgets.Select(attrs={"class": "form-control"}),
                "authors": forms.widgets.SelectMultiple(attrs={"class": "form-control"}),
            }
            error_messages = {  # 设置每个字段的报错提示信息
                "publisher": {
                    "required": "必须给我选一个出版社!"
                }
            }
    3. 实例化
        1. form_obj = BookModelForm()
        2. BookModelForm(instance=book_obj)
        3. BookModelForm(request.POST, instance=book_obj)
    4. 保存
        form_obj.save()

    代码示例

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, HttpResponse
from app01 import models
from app01.forms import BookForm, BookModelForm
# Create your views here.

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):
    form_obj = BookModelForm()
    if request.method == "POST":
        # 从用户提交过来的数据中取数据
        # 做校验
        form_obj = BookModelForm(request.POST)
        if form_obj.is_valid():  # 做数据有效性的校验
            form_obj.save()
            return redirect("/book_list/")
    return render(request, "add_book.html", locals())

def edit_book(request, pk):
    book_obj = models.Book.objects.filter(id=pk).first()
    form_obj = BookModelForm(instance=book_obj)
    if request.method == "POST":
        # 从用户提交过来的数据中取数据
        form_obj = BookModelForm(request.POST, instance=book_obj)
        if form_obj.is_valid():
            # 去数据库更新对应的书籍
            form_obj.save()
            return redirect("/book_list/")
    return render(request, "edit_book.html", locals())

views.py

from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
from app01 import models

# 写一个和Model类一一对应的form
class BookModelForm(forms.ModelForm):
    class Meta:
        model = models.Book
        # fields = "__all__"  # model类里所有的字段都展示
        # fields = ["title", ]  # 指定展示某些字段
        exclude = ["title", ]  # 除了指定字段,其他字段都展示
        labels = {  # 设置label标签名
            "title": "书名",
            "phone": "手机号",
            "publisher": "出版社",
            "authors": "作者",
        }
        widgets = {  # 设置每个字段的插件信息
            "title": forms.widgets.TextInput(attrs={"class": "form-control"}),
            "phone": forms.widgets.TextInput(attrs={"class": "form-control"}),
            "publisher": forms.widgets.Select(attrs={"class": "form-control"}),
            "authors": forms.widgets.SelectMultiple(attrs={"class": "form-control"}),
        }
        error_messages = {  # 设置每个字段的报错提示信息
            "publisher": {
                "required": "必须给我选一个出版社!"
            }
        }

forms.py

<!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>

html-book_list.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>添加书籍</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <h1>添加书籍</h1>

            <form action="" method="post" novalidate autocomplete="off">
                {% for field in form_obj %}
                    <div class="form-group">
                        <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                        {{ field }}
                        <p>{{ field.errors.0 }}</p>
                    </div>
                {% endfor %}
                <input type="submit" class="btn btn-success">
            </form>
        </div>
    </div>
</div>

</body>
</html>

html-add_book.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>编辑书籍</title>
    <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet">
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <h1>编辑书籍</h1>
            <form action="" method="post">
                {% csrf_token %}
                {% for field in form_obj %}
                    <div class="form-group">
                        <label for="{{ field.id_for_label }}">{{ field.label }}</label>
                        {{ field }}
                        <p>{{ field.errors.0 }}</p>
                    </div>
                {% endfor %}
                <input type="submit" class="btn btn-success">
            </form>
        </div>
    </div>
</div>

</body>
</html>

html-edit_book.html

三、auth模块+报障系统(BBS) :https://www.cnblogs.com/liwenzhou/p/9030211.html

原文地址:https://www.cnblogs.com/spf21/p/9559710.html

时间: 2024-10-08 11:43:22

Django进阶三的相关文章

Python进阶(三十六)-Web框架Django项目搭建全过程

Python进阶(三十六)-Web框架Django项目搭建全过程 ??IDE说明: Win7系统 Python:3.5 Django:1.10 Pymysql:0.7.10 Mysql:5.5 ??Django 是由 Python 开发的一个免费的开源网站框架,可以用于快速搭建高性能,优雅的网站! Django 特点 强大的数据库功能 用python的类继承,几行代码就可以拥有一个丰富,动态的数据库操作接口(API),如果需要你也能执行SQL语句. 自带的强大的后台功能 几行简单的代码就让你的网

python 全栈 web框架 Django进阶

django 进阶 基础中,一些操作都是手动创建连接的非主流操作,这样显得太low,当然也是为了熟悉这个框架! 实际中,django自带连接数据库和创建app的机制,同时还有更完善的路由系统机制.既然基础已经了解,那就聊聊主流的东西. 一.web框架重新认知: 既然都是框架,那肯定是都包含了这些模块和对应的功能!但是不同框架之间也是有些诧异,毕竟封装的方法不同. Django: - 路由(url路由系统) - 视图(视图函数) - 模板(模版页面) - 数据库 ---> ORM(类-表:对象-行

django进阶-3

先看效果图: 登陆admin后的界面: 查看作者: 当然你也可以定制admin, 使界面更牛逼 数据库表结构: app01/models.py 1 from django.db import models 2 from django.utils.html import format_html #把字符串变成html 3 4 # Create your models here. 5 class Author(models.Model): 6 first_name = models.CharFiel

【Python全栈-后端开发】Django进阶2-Form表单

Django进阶2-Form表单 Django的Form主要具有一下几大功能: 生成HTML标签(可以保留上次输入内容) 验证用户数据(显示错误信息) HTML Form提交保留上次提交数据 初始化页面显示内容 一.小试牛刀 1.创建Form类 在app01 文件夹下-->创建新的.py 文件 from django.forms import Form from django.forms import widgets from django.forms import fields class M

Java进阶(三十四)Integer与int的种种比较你知道多少?

Java进阶(三十四)Integer与int的种种比较你知道多少? 前言 如果面试官问Integer与int的区别:估计大多数人只会说到两点:Ingeter是int的包装类,注意是一个类:int的初值为0,Ingeter的初值为null.但是如果面试官再问一下Integer i = 1;int ii = 1; i==ii为true还是为false?估计就有一部分人答不出来了,如果再问一下其他的,估计更多的人会头脑一片混乱.所以我对它们进行了总结,希望对大家有帮助. 首先看代码: package

Python爬虫进阶三之Scrapy框架安装配置

初级的爬虫我们利用urllib和urllib2库以及正则表达式就可以完成了,不过还有更加强大的工具,爬虫框架Scrapy,这安装过程也是煞费苦心哪,在此整理如下. Windows 平台: 我的系统是 Win7,首先,你要有Python,我用的是2.7.7版本,Python3相仿,只是一些源文件不同. 官网文档:http://doc.scrapy.org/en/latest/intro/install.html,最权威哒,下面是我的亲身体验过程. 1.安装Python 安装过程我就不多说啦,我的电

3. 蛤蟆的数据结构进阶三静态查询之折半查询

3. 蛤蟆的数据结构进阶三静态查询之折半查询 本篇名言:"但是话不行,要紧的是做. --鲁迅" 继续来看静态查询的折半查询. 欢迎转载,转载请标明出处:http://blog.csdn.net/notbaron/article/details/47211637 1.  折半查找 折半查找要求查找表用顺序存储结构存放且各数据元素按关键字有序(升序或隆序)排列,也就是说折半查找只适用于对有序顺序表进行查找. 折半查找的基本思想是:首先以整个查找表作为查找范围,用查找条件中给定值k与中间位置

Python进阶(三十五)-Fiddler命令行和HTTP断点调试

Python进阶(三十五)-Fiddler命令行和HTTP断点调试 一. Fiddler内置命令 ??上一节(使用Fiddler进行抓包分析)中,介绍到,在web session(与我们通常所说的session不是同一个概念,这里的每条HTTP请求都称为一个session).界面中能够看到Fiddler抓取的全部HTTP请求.而为了更加方便的管理全部的session, Fiddler提供了一系列内置的函数用于筛选和操作这些session(习惯命令行操作Linux的童鞋应该能够感受到这会有多么方便

Python进阶(三十四)-Python3多线程解读

Python进阶(三十四)-Python3多线程解读 线程讲解 ??多线程类似于同时执行多个不同程序,多线程运行有如下优点: 使用线程可以把占据长时间的程序中的任务放到后台去处理. 用户界面可以更加吸引人,这样比如用户点击了一个按钮去触发某些事件的处理,可以弹出一个进度条来显示处理的进度. 程序的运行速度可能加快. 在一些等待的任务实现上如用户输入.文件读写和网络收发数据等,线程就比较有用了.在这种情况下我们可以释放一些珍贵的资源如内存占用等等. ??线程在执行过程中与进程还是有区别的.每个独立