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

  1.   auth模块的常用方法  
    1. authenticate() 用户认证
        from django.contrib import auth
        user = auth.authenticate(request, username='theuser',password='thepassword')
    
    2. login() 生成session
        from django.contrib import auth
        auth.login(request, user)
        
    3. create_user() 创建用户
        from django.contrib.auth.models import User
        user = User.objects.create_user(username='用户名',password='密码',email='邮箱',...)
        
    4. create_superuser()
        from django.contrib.auth.models import User
        user = User.objects.create_superuser(username='用户名',password='密码',email='邮箱',...)
        
    5. logout() 注销用户
        from django.contrib.auth import logout
        def logout_view(request):
            logout(request)
            
    6. check_password() 提供的一个检查密码是否正确的方法,需要提供当前请求用户的密码 密码正确返回True,否则返回False
        ok = user.check_password('密码')
        
    7. set_password() 修改密码
        user.set_password(password='')
        user.save()
        
    8. login_requierd() auth自带的装饰器
        from django.contrib.auth.decorators import login_required
    
        @login_required
        def my_view(request):
          ...
        若用户没有登录,则会跳转到django默认的 登录URL '/accounts/login/ ' 并传递当前访问url的绝对路径 (登陆成功后,会重定向到该路径)。
        如果需要自定义登录的URL,则需要在settings.py文件中通过LOGIN_URL进行修改。
        LOGIN_URL = '/login/'  # 这里配置成你项目登录页面的路由
  2.   扩展默认的auth_user表
    默认auth模块使用的是auth_user表,不满足实际需求
    1. 必须继承AbstractUser  (model.py)
        from django.contrib.auth.models import AbstractUser
        class UserInfo(AbstractUser):
            phone = models.CharField(max_length=11)
            
    2. 告诉Django使用我们的用户表代替auth_user表 (settings.py)
        AUTH_USER_MODEL = "fault_reporting.UserInfo"

四、验证码 

# 安装包 pip3 install Pillow
from
django.shortcuts import render, redirect, HttpResponse from django import views from django.contrib import auth import random # Create your views here. class LoginView(views.View): def get(self, request): return render(request, "login.html") def post(self, request): next_url = request.GET.get("next", "/index/") username = request.POST.get("username") pwd = request.POST.get("password") v_code = request.POST.get("vcode", "").upper() # 先判断验证码正不正确 if v_code == request.session.get("v_code"): user_obj = auth.authenticate(username=username, password=pwd) if user_obj: auth.login(request, user_obj) return redirect(next_url) else: return render(request, "login.html", {"error_msg": "用户名或密码错误"}) else: return render(request, "login.html", {"error_msg": "验证码错误!"}) def index(request): return render(request, "index.html") # 专门返回验证码图片的视图函数 def vcode(request): from PIL import Image, ImageDraw, ImageFont # 定义一个生成随机颜色代码的函数 def random_color(): return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255) # 创建一个随机颜色的图片对象 image_obj = Image.new( "RGB", (250, 35), random_color() ) # 在该图片对象上生成一个画笔对象 draw_obj = ImageDraw.Draw(image_obj) # 加载一个字体对象 font_obj = ImageFont.truetype('static/font/kumo.ttf', 28) tmp = [] for i in range(5): l = chr(random.randint(97, 122)) # 生成随机的小写字母 u = chr(random.randint(65, 90)) # 生成随机的大写字母 n = str(random.randint(0, 9)) # 生成一个随机的数字 # 从上面三个随机选一个 r = random.choice([l, u, n]) # 将选中过的那个字符写到图片上 draw_obj.text((40*i+30, 0), r, fill=random_color(), font=font_obj) tmp.append(r) # # 加干扰线 # width = 250 # 图片宽度(防止越界) # height = 35 # for i in range(5): # x1 = random.randint(0, width) # x2 = random.randint(0, width) # y1 = random.randint(0, height) # y2 = random.randint(0, height) # draw_obj.line((x1, y1, x2, y2), fill=random_color()) # # # 加干扰点 # for i in range(40): # draw_obj.point([random.randint(0, width), random.randint(0, height)], fill=random_color()) # x = random.randint(0, width) # y = random.randint(0, height) # draw_obj.arc((x, y, x+4, y+4), 0, 90, fill=random_color()) v_code = "".join(tmp).upper() # 将生成的验证码保存 request.session["v_code"] = v_code # 直接在内存中保存图片替代io操作 from io import BytesIO f1 = BytesIO() image_obj.save(f1, format="PNG") img_data = f1.getvalue() return HttpResponse(img_data, content_type="image/png")
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>欢迎登陆</title>
    <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/my-style.css">
</head>
<body>

<div class="container">
    <div class="row">
        <div class="col-md-6 col-md-offset-3 login-box">
            <h3>请登陆</h3>
            <form action="" method="post">
                {% csrf_token %}
                <div class="form-group">
                    <label for="id_username">用户名</label>
                    <input type="text" class="form-control" id="id_username" name="username" placeholder="用户名">
                </div>
                <div class="form-group">
                    <label for="id_password">密码</label>
                    <input type="password" class="form-control" id="id_password" name="password" placeholder="密码">
                </div>
                <div class="form-group">
                    <label for="id_vcode" style="display: block">验证码</label>
                    <input type="text" class="form-control" id="id_vcode" name="vcode" placeholder="验证码" style="width: 250px;display: inline-block">
                    <img src="/vcode/"  id="v-code-img" style="width: 250px;height: 35px;display: inline-block;float: right">
                </div>
                <button type="submit" class="btn btn-success">登陆</button>
                <p class="login-error">{{ error_msg }}</p>
            </form>
        </div>
    </div>
</div>
<script src="/static/plugins/jquery-3.3.1.min.js"></script>
<script>
    $(".login-box input").focus(function () {
        $(".login-error").text("");
    });
    $("#v-code-img").click(function () {
        this.src += "?";
    });
</script>
</body>
</html>

 

posted @ 2018-08-30 13:49  S.Curry  阅读(255)  评论(0编辑  收藏  举报