Django学习第三天

python manage.py runserver

使用以上的命令启动项目

实现新建用户数据功能

views.py文件代码

from django.shortcuts import render, redirect
from app01 import models


# Create your views here.
def depart_list(request):
    """ 部门列表 """
    queryset = models.Department.objects.all()

    return render(request,
                  'depart_list.html',
                  {'queryset': queryset})


def depart_add(request):
    """ 添加部门 """
    if request.method == "GET":
        return render(request,
                      'depart_add.html')

    # 获取用户POST提交过来的数据(title输入为空)
    title = request.POST.get("title")

    # 保存到数据库
    models.Department.objects.create(title=title)

    # 重定向回部门列表
    return redirect("/depart/list/")


def depart_delete(request):
    """ 删除部门 """
    # 获取ID http://127.0.0.1:8000/depart/delete/?nid=
    nid = request.GET.get("nid")

    # 删除
    models.Department.objects.filter(id=nid).delete()

    # 重定向回部门列表
    return redirect("/depart/list/")


def depart_edit(request, nid):
    """ 修改部门 """
    if request.method == "GET":
        # 根据nid,获取他的数据 [obj,]
        row_object = models.Department.objects.filter(id=nid).first()

        return render(request, "depart_edit.html", {"row_object": row_object})

    # 获取用户POST提交过来的数据(title输入为空)
    title = request.POST.get("title")

    # 保存到数据库
    models.Department.objects.filter(id=nid).update(title=title)

    # 重定向回部门列表
    return redirect("/depart/list/")


def user_list(request):
    """ 用户管理 """

    # 获取所有用户列表
    queryset = models.UserInfo.objects.all()

    # 用python的语法获取数据
    # for obj in queryset:
    #     print(obj.id, obj.name, obj.account, obj.create_time.strftime("%Y-%m-%d"), obj.gender, obj.get_gender_display()
    #     , obj.depart_id, obj.depart.title)
    #     obj.depart_id # 获取数据库中存储的那个字段的值
    #     obj.depart.title # 根据id自动去关联的表中获取一行数据depart对象

    return render(request, "user_list.html", {"queryset": queryset})


def user_add(request):
    """ 添加用户 """

    if request.method == "GET":
        context = {
            'gender_choices': models.UserInfo.gender_choices,
            'depart_list': models.Department.objects.all()
        }
        return render(request, 'user_add.html',
                      {"gender_choices": context["gender_choices"], "depart_list": context["depart_list"]})

    # 获取用户提交的数据
    user = request.POST.get("user")
    pwd = request.POST.get("pwd")
    age = request.POST.get("age")
    account = request.POST.get("ac")
    ctime = request.POST.get("ctime")
    gender_id = request.POST.get("gd")
    depart_id = request.POST.get("dp")

    # 添加到数据库中
    models.UserInfo.objects.create(name=user, password=pwd, age=age,
                                   account=account, create_time=ctime,
                                   gender=gender_id, depart_id=depart_id)

    # 返回到用户列表页面
    return redirect("/user/list/")

user_add.html代码内容

{% extends 'layout.html' %}

{% block content %}
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">新建用户</h3>
            </div>
            <div class="panel-body">
                <form method="post">
                    {% csrf_token %}
                    <div class="form-group">
                        <label>姓名</label>
                        <input type="text" class="form-control" placeholder="姓名" name="user">
                    </div>
                    <div class="form-group">
                        <label>密码</label>
                        <input type="text" class="form-control" placeholder="密码" name="pwd">
                    </div>
                    <div class="form-group">
                        <label>年龄</label>
                        <input type="text" class="form-control" placeholder="年龄" name="age">
                    </div>
                    <div class="form-group">
                        <label>余额</label>
                        <input type="text" class="form-control" placeholder="余额" name="ac">
                    </div>
                    <div class="form-group">
                        <label>入职时间</label>
                        <input type="text" class="form-control" placeholder="入职时间" name="ctime">
                    </div>
                    <div class="form-group">
                        <label>性别</label>
                        <select class="form-control" name="gd">
                            {% for item in gender_choices %}
                                <option value="{{ item.0 }}">{{ item.1 }}</option>
                            {% endfor %}
                        </select>
                    </div>
                    <div class="form-group">
                        <label>部门</label>
                        <select class="form-control" name="dp">
                            {% for item in depart_list %}
                                <option value="{{ item.id }}">{{ item.title }}</option>
                            {% endfor %}
                        </select>
                    </div>

                    <button type="submit" class="btn btn-primary">提 交</button>
                </form>
            </div>
        </div>
    </div>
{% endblock %}

输入日期数据显示错误信息

原因,数据格式不对

# 包含年月日,时分秒
    # create_time = models.DateTimeField(verbose_name="入职时间")

正确的日期测试数据格式(2024-07-03 13:30)

数据库时间设置(不包含时分秒的格式)

新建用户:

原始方式处理思路:不会采用(本质)【麻烦】

--用户提交数据没有校验

--错误,页面上应该有错误提示

--页面上,每一个字段都需要我们重新写一遍

--关联的数据,手动去获取并展示循环展示在页面

Django组件

--Form组件(小简便)

--ModelForm组件(最简便)

初识Form和ModelForm

0.models.py

from django.db import models


# Create your models here.
class Department(models.Model):
    """ 部门表 """
    title = models.CharField(verbose_name='标题', max_length=32)


class UserInfo(models.Model):
    """ 员工表 """
    name = models.CharField(verbose_name="姓名", max_length=16)
    password = models.CharField(verbose_name="密码", max_length=64)
    age = models.IntegerField(verbose_name="年龄")
    account = models.DecimalField(verbose_name="账户余额", max_digits=10, decimal_places=2, default=0)
    create_time = models.DateTimeField(verbose_name="入职时间")

    # 无约束
    # depart_id = models.BigIntegerField(verbose_name="部门ID")

    # 1.有约束
    # -to, 与哪张表关联
    # -to_field, 表中的哪一列关联
    # 2.django自动
    # -写的depart
    # -生成数据列depart_id
    # 3.部门表被删除
    # 3.1 级联删除
    depart = models.ForeignKey(to="Department", to_field="id", on_delete=models.CASCADE)
    # 3.2 置空
    # depart = models.ForeignKey(to="Department", to_field="id", null=True, blank=True, on_delete=models.SET_NULL)

    # 在django中做的约束
    gender_choices = (
        (1, "男"),
        (2, "女"),
    )
    gender = models.SmallIntegerField(verbose_name="性别", choices=gender_choices)

1.views.py

#ModelForm
class MyForm(ModelForm):
    # 可以使用自定义字段
    xx = form.CharField*("...")
    class Meta:
        model = UserInfo
        fields = ["name","password","age","xx"]

# Form
class MyForm(Form):
    user = forms.CharField(widget=forms.Input)
    pwd = forms.CharField(widget=forms.Input)
    email = forms.CharField(widget=forms.Input)

def user_add(request):
    if request.method == "GET":
        form = MyForm()
        return render(request, 'user_add.html', {"form": form})

2.user_add.html

<form method="post">
    {{ form.user }}
    {{ form.pwd }}
    {{ form.email }}
    <!--代替-->
    <input type="text" class="form-control" placeholder="姓名" name="user" />
</form>
<!-- 还可以这么写 -->
<form method="post">
    {% for field in form %}
        {{ field }}
    {% endfor %}
</form>

ModelForm输入框增加样式

更为简洁的办法

class UserModelForm(forms.ModelForm):
    class Meta:
        model = models.UserInfo
        fields = ["name", "password", "age", "account", "create_time", "gender", "depart"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环找到所有的插件,添加class="form-control"样式
        for name, field in self.fields.items():
            # # 判断某个字段不加
            # if name == "password":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

这个字段是用来定义输入框默认值的

这个用来关闭游览器做校验

自定义校验规则(用户名最小长度为3)

数据校验

def user_model_form_add(request):
    """ 添加用户(ModelForm版本) """
    if request.method == "GET":
        form = UserModelForm()
        return render(request, 'user_model_form_add.html', {"form": form})

    # 用户POST提交数据,数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/user/list/")

    # 校验失败(在页面上显示错误信息)
    return render(request, 'user_model_form_add.html', {"form": form})

校验提示信息为英文解决方案settings.py文件中

LANGUAGE_CODE = 'zh-hans'

user_model_form_add.html代码内容
{% extends 'layout.html' %}

{% block content %}
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">新建用户</h3>
            </div>
            <div class="panel-body">
                <form method="post" novalidate>
                    {% csrf_token %}
                    {% for field in form %}
                        <div class="form-group">
                            <label>{{ field.label }}</label>
                            {{ field }}
                            <span style="color: red;">{{ field.errors.0 }}</span>
                        </div>
                    {% endfor %}

                    <button type="submit" class="btn btn-primary">提 交</button>
                </form>
            </div>
        </div>
    </div>
{% endblock %}

views.py代码内容

from django.shortcuts import render, redirect
from app01 import models


# Create your views here.
def depart_list(request):
    """ 部门列表 """
    queryset = models.Department.objects.all()

    return render(request,
                  'depart_list.html',
                  {'queryset': queryset})


def depart_add(request):
    """ 添加部门 """
    if request.method == "GET":
        return render(request,
                      'depart_add.html')

    # 获取用户POST提交过来的数据(title输入为空)
    title = request.POST.get("title")

    # 保存到数据库
    models.Department.objects.create(title=title)

    # 重定向回部门列表
    return redirect("/depart/list/")


def depart_delete(request):
    """ 删除部门 """
    # 获取ID http://127.0.0.1:8000/depart/delete/?nid=
    nid = request.GET.get("nid")

    # 删除
    models.Department.objects.filter(id=nid).delete()

    # 重定向回部门列表
    return redirect("/depart/list/")


def depart_edit(request, nid):
    """ 修改部门 """
    if request.method == "GET":
        # 根据nid,获取他的数据 [obj,]
        row_object = models.Department.objects.filter(id=nid).first()

        return render(request, "depart_edit.html", {"row_object": row_object})

    # 获取用户POST提交过来的数据(title输入为空)
    title = request.POST.get("title")

    # 保存到数据库
    models.Department.objects.filter(id=nid).update(title=title)

    # 重定向回部门列表
    return redirect("/depart/list/")


def user_list(request):
    """ 用户管理 """

    # 获取所有用户列表
    queryset = models.UserInfo.objects.all()

    # 用python的语法获取数据
    # for obj in queryset:
    #     print(obj.id, obj.name, obj.account, obj.create_time.strftime("%Y-%m-%d"), obj.gender, obj.get_gender_display()
    #     , obj.depart_id, obj.depart.title)
    #     obj.depart_id # 获取数据库中存储的那个字段的值
    #     obj.depart.title # 根据id自动去关联的表中获取一行数据depart对象

    return render(request, "user_list.html", {"queryset": queryset})


def user_add(request):
    """ 添加用户 """

    if request.method == "GET":
        context = {
            'gender_choices': models.UserInfo.gender_choices,
            'depart_list': models.Department.objects.all()
        }
        return render(request, 'user_add.html',
                      {"gender_choices": context["gender_choices"], "depart_list": context["depart_list"]})

    # 获取用户提交的数据
    user = request.POST.get("user")
    pwd = request.POST.get("pwd")
    age = request.POST.get("age")
    account = request.POST.get("ac")
    ctime = request.POST.get("ctime")
    gender_id = request.POST.get("gd")
    depart_id = request.POST.get("dp")

    # 添加到数据库中
    models.UserInfo.objects.create(name=user, password=pwd, age=age,
                                   account=account, create_time=ctime,
                                   gender=gender_id, depart_id=depart_id)

    # 返回到用户列表页面
    return redirect("/user/list/")


from django import forms


# ModelForm示例
class UserModelForm(forms.ModelForm):
    name = forms.CharField(min_length=3, label="用户名")

    class Meta:
        model = models.UserInfo
        fields = ["name", "password", "age", "account", "create_time", "gender", "depart"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环找到所有的插件,添加class="form-control"样式
        for name, field in self.fields.items():
            # # 判断某个字段不加
            # if name == "password":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


def user_model_form_add(request):
    """ 添加用户(ModelForm版本) """
    if request.method == "GET":
        form = UserModelForm()
        return render(request, 'user_model_form_add.html', {"form": form})

    # 用户POST提交数据,数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/user/list/")

    # 校验失败(在页面上显示错误信息)
    return render(request, 'user_model_form_add.html', {"form": form})

编辑用户功能实现

点击编辑,跳转到编辑页面(将编辑行的ID携带过去)

编辑页面(默认数据,根据ID获取并设置到页面中)

提交(错误提示,数据校验,在数据库更新)

以前的实现方式

model.UserInfo.filter(id=4).update(...)

使用ModelForm

def user_edit(request, nid):
    """ 编辑用户 """

    # 根据ID去数据库获取要编辑的那一行数据
    row_object = models.UserInfo.objects.filter(id=nid).first()

    form = UserModelForm(instance=row_object)
    return render(request, 'user_edit.html', {'form': form})
user_edit.html代码内容
{% entends layout.html %}

{% block content %}
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">编辑用户</h3>
            </div>
            <div class="panel-body">
                <form method="post" novalidate>
                    {% csrf_token %}
                    {% for field in form %}
                        <div class="form-group">
                            <label>{{ field.label }}</label>
                            {{ field }}
                            <span style="color: red;">{{ field.errors.0 }}</span>
                        </div>
                    {% endfor %}

                    <button type="submit" class="btn btn-primary">提 交</button>
                </form>
            </div>
        </div>
    </div>
{% endblock %}

代表不是增加数据而是在当前保存修改数据到当前行中这么写

def user_edit(request, nid):
    """ 编辑用户 """
    row_object = models.UserInfo.objects.filter(id=nid).first()
    
    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据

        form = UserModelForm(instance=row_object)
        return render(request, 'user_edit.html', {'form': form})

    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/user/list/')
    return render(request, 'user_edit.html', {"form": form})

可以额外增加一些字段

def user_edit(request, nid):
    """ 编辑用户 """
    row_object = models.UserInfo.objects.filter(id=nid).first()

    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据

        form = UserModelForm(instance=row_object)
        return render(request, 'user_edit.html', {'form': form})

    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        # 默认保存的是用户输入的所有数据,如果想要在用户输入以外增加一点值
        # form.instance.字段名 = 值
        form.save()
        return redirect('/user/list/')
    return render(request, 'user_edit.html', {"form": form})

靓号管理数据库设计

class PrettyNum(models.Model):
    """ 靓号表 """
    mobile = models.CharField(verbose_name="手机号", max_length=11)
    #想要允许为空 null=True, blank=True
    price = models.IntegerField(verbose_name="价格", default=0)

    level_choices = (
        (1, "1级"),
        (2, "2级"),
        (3, "3级"),
        (4, "4级"),
    )
    level = models.SmallIntegerField(verbose_name="级别", choices=level_choices, default=1)

    status_choices = (
        (1, "已占用"),
        (2, "未使用"),
    )
    status = models.SmallIntegerField(verbose_name="状态", choices=status_choices, default=2)

修改了数据库内容要执行命令语句

 运行创建数据库代码的命令语句

 python manage.py makemigrations
 python manage.py migrate 

数据库这么定义的数据展示在页面上对应的代码

拿到倒序的level选择框数据

def pretty_list(request):
    """ 靓号列表 """

    # select * from 表 order by level desc;
    queryset = models.PrettyNum.objects.all().order_by("-level")

    return render(request, 'pretty_list.html', {"queryset": queryset})

新建靓号

列表点击跳转:/pretty/add/

URL

ModelForm类

from django import forms

class PrettyModelForm(forms.ModelForm):
    ...

函数

--实例化类的对象

--通过render将对象传入到HTML中

--模板的循环展示所有的字段

点击提交

--数据校验

--保存到数据库

--跳转回靓号列表

匹配数据格式使用正则表达式提示格式错误(方式1)

匹配数据格式使用钩子方法提示格式错误(方式2)

from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError

class PrettyModelForm(forms.ModelForm):
    # 验证:方式1
    # mobile = forms.CharField(
    #     label="手机号",
    #     validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
    # )

    class Meta:
        model = models.PrettyNum
        # 使用所有字段
        # fields = "__all__"
        # 使用自定义哪些字段
        fields = ["mobile", "price", "level", "status"]
        # 排除某个字段
        # exclude = ['level']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环找到所有的插件,添加class="form-control"样式
        for name, field in self.fields.items():
            # # 判断某个字段不加
            # if name == "password":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    # 验证:方式2
    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]
        if len(txt_mobile) != 11:
            raise ValidationError("格式错误")

        # 验证通过,用户输入的值返回
        return txt_mobile

views.py新建靓号代码

from django.core.validators import RegexValidator


class PrettyModelForm(forms.ModelForm):
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
    )

    class Meta:
        model = models.PrettyNum
        # 使用所有字段
        # fields = "__all__"
        # 使用自定义哪些字段
        fields = ["mobile", "price", "level", "status"]
        # 排除某个字段
        # exclude = ['level']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环找到所有的插件,添加class="form-control"样式
        for name, field in self.fields.items():
            # # 判断某个字段不加
            # if name == "password":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


def pretty_add(request):
    """ 添加靓号 """
    if request.method == "GET":
        form = PrettyModelForm()
        return render(request, 'pretty_add.html', {"form": form})

    # 用户POST提交数据,数据校验
    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")

    # 校验失败(在页面上显示错误信息)
    return render(request, 'pretty_add.html', {"form": form})

pretty_add.html代码内容

{% extends 'layout.html' %}

{% block content %}
    <div class="container">
        <div class="panel panel-default">
            <div class="panel-heading">
                <h3 class="panel-title">新建靓号</h3>
            </div>
            <div class="panel-body">
                <form method="post" novalidate>
                    {% csrf_token %}
                    {% for field in form %}
                        <div class="form-group">
                            <label>{{ field.label }}</label>
                            {{ field }}
                            <span style="color: red;">{{ field.errors.0 }}</span>
                        </div>
                    {% endfor %}

                    <button type="submit" class="btn btn-primary">提 交</button>
                </form>
            </div>
        </div>
    </div>
{% endblock %}

实现url跳转别忘记修改pretty_list.html里面的内容

实现靓号修改的功能(包含不允许手机号重复)

不允许手机号存在

设置手机号不可编辑

正则表达式匹配数据格式校验,钩子函数判断手机号是否已经存在

数据删除代码实现

搜索手机号

models.PrettyNum.objects.filter(mobile="19999999999", id=12)

data_dict = {"mobile":"19999999999","id":123}
models.PrettyNum.objects.filter(**data_dict)
models.PrettyNum.objects.filter(id=12)    # 等于12
models.PrettyNum.objects.filter(id__gt=12)    # 大于12
models.PrettyNum.objects.filter(id__gte=12)    # 大于等于12
models.PrettyNum.objects.filter(id__lt=12)    # 小于12
models.PrettyNum.objects.filter(id__lte=12)    # 小于等于12

搜索功能实现

views.py代码内容

from django.shortcuts import render, redirect

from app01 import models


# Create your views here.
def depart_list(request):
    """ 部门列表 """
    queryset = models.Department.objects.all()

    return render(request,
                  'depart_list.html',
                  {'queryset': queryset})


def depart_add(request):
    """ 添加部门 """
    if request.method == "GET":
        return render(request,
                      'depart_add.html')

    # 获取用户POST提交过来的数据(title输入为空)
    title = request.POST.get("title")

    # 保存到数据库
    models.Department.objects.create(title=title)

    # 重定向回部门列表
    return redirect("/depart/list/")


def depart_delete(request):
    """ 删除部门 """
    # 获取ID http://127.0.0.1:8000/depart/delete/?nid=
    nid = request.GET.get("nid")

    # 删除
    models.Department.objects.filter(id=nid).delete()

    # 重定向回部门列表
    return redirect("/depart/list/")


def depart_edit(request, nid):
    """ 修改部门 """
    if request.method == "GET":
        # 根据nid,获取他的数据 [obj,]
        row_object = models.Department.objects.filter(id=nid).first()

        return render(request, "depart_edit.html", {"row_object": row_object})

    # 获取用户POST提交过来的数据(title输入为空)
    title = request.POST.get("title")

    # 保存到数据库
    models.Department.objects.filter(id=nid).update(title=title)

    # 重定向回部门列表
    return redirect("/depart/list/")


def user_list(request):
    """ 用户管理 """

    # 获取所有用户列表
    queryset = models.UserInfo.objects.all()

    # 用python的语法获取数据
    # for obj in queryset:
    #     print(obj.id, obj.name, obj.account, obj.create_time.strftime("%Y-%m-%d"), obj.gender, obj.get_gender_display()
    #     , obj.depart_id, obj.depart.title)
    #     obj.depart_id # 获取数据库中存储的那个字段的值
    #     obj.depart.title # 根据id自动去关联的表中获取一行数据depart对象

    return render(request, "user_list.html", {"queryset": queryset})


def user_add(request):
    """ 添加用户 """

    if request.method == "GET":
        context = {
            'gender_choices': models.UserInfo.gender_choices,
            'depart_list': models.Department.objects.all()
        }
        return render(request, 'user_add.html',
                      {"gender_choices": context["gender_choices"], "depart_list": context["depart_list"]})

    # 获取用户提交的数据
    user = request.POST.get("user")
    pwd = request.POST.get("pwd")
    age = request.POST.get("age")
    account = request.POST.get("ac")
    ctime = request.POST.get("ctime")
    gender_id = request.POST.get("gd")
    depart_id = request.POST.get("dp")

    # 添加到数据库中
    models.UserInfo.objects.create(name=user, password=pwd, age=age,
                                   account=account, create_time=ctime,
                                   gender=gender_id, depart_id=depart_id)

    # 返回到用户列表页面
    return redirect("/user/list/")


from django import forms


# ModelForm示例
class UserModelForm(forms.ModelForm):
    name = forms.CharField(min_length=3, label="用户名")

    class Meta:
        model = models.UserInfo
        fields = ["name", "password", "age", "account", "create_time", "gender", "depart"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环找到所有的插件,添加class="form-control"样式
        for name, field in self.fields.items():
            # # 判断某个字段不加
            # if name == "password":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


def user_model_form_add(request):
    """ 添加用户(ModelForm版本) """
    if request.method == "GET":
        form = UserModelForm()
        return render(request, 'user_model_form_add.html', {"form": form})

    # 用户POST提交数据,数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/user/list/")

    # 校验失败(在页面上显示错误信息)
    return render(request, 'user_model_form_add.html', {"form": form})


def user_edit(request, nid):
    """ 编辑用户 """
    row_object = models.UserInfo.objects.filter(id=nid).first()

    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据

        form = UserModelForm(instance=row_object)
        return render(request, 'user_edit.html', {'form': form})

    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        # 默认保存的是用户输入的所有数据,如果想要在用户输入以外增加一点值
        # form.instance.字段名 = 值
        form.save()
        return redirect('/user/list/')
    return render(request, 'user_edit.html', {"form": form})


def user_delete(request, nid):
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list/')


def pretty_list(request):
    """ 靓号列表 """
    data_dict = {}
    search_data = request.GET.get('q', "")
    if search_data:
        data_dict["mobile__contains"] = search_data

    # select * from 表 order by level desc;
    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")

    return render(request, 'pretty_list.html', {"queryset": queryset, "search_data": search_data})


from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError


class PrettyModelForm(forms.ModelForm):
    # 验证:方式1
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
    )

    class Meta:
        model = models.PrettyNum
        # 使用所有字段
        # fields = "__all__"
        # 使用自定义哪些字段
        fields = ["mobile", "price", "level", "status"]
        # 排除某个字段
        # exclude = ['level']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环找到所有的插件,添加class="form-control"样式
        for name, field in self.fields.items():
            # # 判断某个字段不加
            # if name == "password":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    # 验证:方式2
    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]

        exists = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号已存在")

        # 验证通过,用户输入的值返回
        return txt_mobile


def pretty_add(request):
    """ 添加靓号 """
    if request.method == "GET":
        form = PrettyModelForm()
        return render(request, 'pretty_add.html', {"form": form})

    # 用户POST提交数据,数据校验
    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")

    # 校验失败(在页面上显示错误信息)
    return render(request, 'pretty_add.html', {"form": form})


class PrettyEditModelForm(forms.ModelForm):
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
    )

    class Meta:
        model = models.PrettyNum
        fields = ["mobile", "price", "level", "status"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    # 验证:方式2
    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]

        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号已存在")

        # 验证通过,用户输入的值返回
        return txt_mobile


def pretty_edit(request, nid):
    """ 编辑靓号 """
    row_object = models.PrettyNum.objects.filter(id=nid).first()

    if request.method == "GET":
        form = PrettyEditModelForm(instance=row_object)
        return render(request, 'pretty_edit.html', {"form": form})

    form = PrettyModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')

    return render(request, 'pretty_edit.html', {"form": form})


def pretty_delete(request, nid):
    """ 删除靓号 """
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect('/pretty/list/')

pretty_list.html代码内容

{% extends 'layout.html' %}

{% block content %}
<div class="container">
    <div style="margin-bottom: 10px" class="clearfix">
        <a class="btn btn-success" href="/pretty/add/" target="_blank">
            <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
            新建靓号
        </a>

        <div style="float: right;width: 300px;">
            <form method="get">
                <div class="input-group">
                    <input type="text" name="q" class="form-control" placeholder="Search for..." value="{{ search_data }}">
                    <span class="input-group-btn">
                        <button class="btn btn-default" type="submit">
                            <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
                        </button>
                    </span>
                </div>
            </form>
        </div>
    </div>

    <div class="panel panel-default">
        <!-- Default panel contents -->
        <div class="panel-heading">
            <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
            靓号列表
        </div>

        <!-- Table -->
        <table class="table table-bordered">
            <thead>
            <tr>
                <th>ID</th>
                <th>号码</th>
                <th>价格</th>
                <th>级别</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            {% for obj in queryset %}
            <tr>
                <th>{{ obj.id }}</th>
                <td>{{ obj.mobile }}</td>
                <td>{{ obj.price }}</td>
                <td>{{ obj.get_level_display }}</td>
                <td>{{ obj.get_status_display }}</td>
                <td>
                    <a class="btn btn-primary btn-xs" href="/pretty/{{ obj.id }}/edit/">编辑</a>
                    <a class="btn btn-danger btn-xs" href="/pretty/{{ obj.id }}/delete/">删除</a>
                </td>
            </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>
</div>
{% endblock %}

分页功能实现

提供了切片操作获取部分数据

页码设置

分页功能杂乱实现

view.py

from django.shortcuts import render, redirect

from app01 import models


# Create your views here.
def depart_list(request):
    """ 部门列表 """
    queryset = models.Department.objects.all()

    return render(request,
                  'depart_list.html',
                  {'queryset': queryset})


def depart_add(request):
    """ 添加部门 """
    if request.method == "GET":
        return render(request,
                      'depart_add.html')

    # 获取用户POST提交过来的数据(title输入为空)
    title = request.POST.get("title")

    # 保存到数据库
    models.Department.objects.create(title=title)

    # 重定向回部门列表
    return redirect("/depart/list/")


def depart_delete(request):
    """ 删除部门 """
    # 获取ID http://127.0.0.1:8000/depart/delete/?nid=
    nid = request.GET.get("nid")

    # 删除
    models.Department.objects.filter(id=nid).delete()

    # 重定向回部门列表
    return redirect("/depart/list/")


def depart_edit(request, nid):
    """ 修改部门 """
    if request.method == "GET":
        # 根据nid,获取他的数据 [obj,]
        row_object = models.Department.objects.filter(id=nid).first()

        return render(request, "depart_edit.html", {"row_object": row_object})

    # 获取用户POST提交过来的数据(title输入为空)
    title = request.POST.get("title")

    # 保存到数据库
    models.Department.objects.filter(id=nid).update(title=title)

    # 重定向回部门列表
    return redirect("/depart/list/")


def user_list(request):
    """ 用户管理 """

    # 获取所有用户列表
    queryset = models.UserInfo.objects.all()

    # 用python的语法获取数据
    # for obj in queryset:
    #     print(obj.id, obj.name, obj.account, obj.create_time.strftime("%Y-%m-%d"), obj.gender, obj.get_gender_display()
    #     , obj.depart_id, obj.depart.title)
    #     obj.depart_id # 获取数据库中存储的那个字段的值
    #     obj.depart.title # 根据id自动去关联的表中获取一行数据depart对象

    return render(request, "user_list.html", {"queryset": queryset})


def user_add(request):
    """ 添加用户 """

    if request.method == "GET":
        context = {
            'gender_choices': models.UserInfo.gender_choices,
            'depart_list': models.Department.objects.all()
        }
        return render(request, 'user_add.html',
                      {"gender_choices": context["gender_choices"], "depart_list": context["depart_list"]})

    # 获取用户提交的数据
    user = request.POST.get("user")
    pwd = request.POST.get("pwd")
    age = request.POST.get("age")
    account = request.POST.get("ac")
    ctime = request.POST.get("ctime")
    gender_id = request.POST.get("gd")
    depart_id = request.POST.get("dp")

    # 添加到数据库中
    models.UserInfo.objects.create(name=user, password=pwd, age=age,
                                   account=account, create_time=ctime,
                                   gender=gender_id, depart_id=depart_id)

    # 返回到用户列表页面
    return redirect("/user/list/")


from django import forms


# ModelForm示例
class UserModelForm(forms.ModelForm):
    name = forms.CharField(min_length=3, label="用户名")

    class Meta:
        model = models.UserInfo
        fields = ["name", "password", "age", "account", "create_time", "gender", "depart"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环找到所有的插件,添加class="form-control"样式
        for name, field in self.fields.items():
            # # 判断某个字段不加
            # if name == "password":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


def user_model_form_add(request):
    """ 添加用户(ModelForm版本) """
    if request.method == "GET":
        form = UserModelForm()
        return render(request, 'user_model_form_add.html', {"form": form})

    # 用户POST提交数据,数据校验
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/user/list/")

    # 校验失败(在页面上显示错误信息)
    return render(request, 'user_model_form_add.html', {"form": form})


def user_edit(request, nid):
    """ 编辑用户 """
    row_object = models.UserInfo.objects.filter(id=nid).first()

    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据

        form = UserModelForm(instance=row_object)
        return render(request, 'user_edit.html', {'form': form})

    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        # 默认保存的是用户输入的所有数据,如果想要在用户输入以外增加一点值
        # form.instance.字段名 = 值
        form.save()
        return redirect('/user/list/')
    return render(request, 'user_edit.html', {"form": form})


def user_delete(request, nid):
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect('/user/list/')


from django.utils.safestring import mark_safe
def pretty_list(request):
    """ 靓号列表 """
    data_dict = {}
    search_data = request.GET.get('q', "")
    if search_data:
        data_dict["mobile__contains"] = search_data

    # 1.根据用户想要访问的页码,计算出起止位置
    page = int(request.GET.get('page', 1))
    page_size = 10
    start = (page - 1) * page_size
    end = page * page_size

    # select * from 表 order by level desc;
    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")[start:end]

    # 数据总条数
    total_count = models.PrettyNum.objects.filter(**data_dict).order_by("-level").count()

    # 总页码
    total_page_count, div = divmod(total_count, page_size)
    if div:
        total_page_count += 1

    #计算出,显示当前页的前5页,后5页
    plus = 5
    if total_page_count <= 2 * plus + 1:
        # 数据库中的数据比较少,都没有达到11页
        start_page = 1
        end_page = total_page_count + 1
    else:
        # 当前页<5时
        if page <= plus:
            start_page = 1
            end_page = 2 * plus + 1
        else:
            if (page + plus) > total_page_count:
                start_page = total_page_count - 2 * plus
                end_page = total_page_count
            else:
                # 数据库中的数据比较多>11页
                start_page = page - plus
                end_page = page + plus + 1

    # 页码
    page_str_list = []

    # 上一页
    if page > 1:
        prev = '<li><a href="?page={}">上一页</a></li>'.format(page - 1)
    else:
        prev = '<li><a href="?page={}">上一页</a></li>'.format(1)
    page_str_list.append(prev)

    for i in range(start_page, end_page):
        if i == page:
            ele = '<li class="active"><a href="?page={}">{}</a></li>'.format(i, i)
        else:
            ele = '<li><a href="?page={}">{}</a></li>'.format(i, i)
        page_str_list.append(ele)

    page_str_list.append('<li><a href="?page={}">首页</a></li>'.format(1))

    # 下一页
    if page < total_page_count:
        prev = '<li><a href="?page={}">下一页</a></li>'.format(page + 1)
    else:
        prev = '<li><a href="?page={}">下一页</a></li>'.format(total_page_count)
    page_str_list.append(prev)

    page_str_list.append('<li><a href="?page={}">尾页</a></li>'.format(total_page_count))

    page_string = mark_safe("".join(page_str_list))

    return render(request, 'pretty_list.html', {"queryset": queryset, "search_data": search_data, "page_string": page_string})


from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError


class PrettyModelForm(forms.ModelForm):
    # 验证:方式1
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
    )

    class Meta:
        model = models.PrettyNum
        # 使用所有字段
        # fields = "__all__"
        # 使用自定义哪些字段
        fields = ["mobile", "price", "level", "status"]
        # 排除某个字段
        # exclude = ['level']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # 循环找到所有的插件,添加class="form-control"样式
        for name, field in self.fields.items():
            # # 判断某个字段不加
            # if name == "password":
            #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    # 验证:方式2
    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]

        exists = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号已存在")

        # 验证通过,用户输入的值返回
        return txt_mobile


def pretty_add(request):
    """ 添加靓号 """
    if request.method == "GET":
        form = PrettyModelForm()
        return render(request, 'pretty_add.html', {"form": form})

    # 用户POST提交数据,数据校验
    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/pretty/list/")

    # 校验失败(在页面上显示错误信息)
    return render(request, 'pretty_add.html', {"form": form})


class PrettyEditModelForm(forms.ModelForm):
    mobile = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
    )

    class Meta:
        model = models.PrettyNum
        fields = ["mobile", "price", "level", "status"]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    # 验证:方式2
    def clean_mobile(self):
        txt_mobile = self.cleaned_data["mobile"]

        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
        if exists:
            raise ValidationError("手机号已存在")

        # 验证通过,用户输入的值返回
        return txt_mobile


def pretty_edit(request, nid):
    """ 编辑靓号 """
    row_object = models.PrettyNum.objects.filter(id=nid).first()

    if request.method == "GET":
        form = PrettyEditModelForm(instance=row_object)
        return render(request, 'pretty_edit.html', {"form": form})

    form = PrettyModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/pretty/list/')

    return render(request, 'pretty_edit.html', {"form": form})


def pretty_delete(request, nid):
    """ 删除靓号 """
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect('/pretty/list/')
pretty_list.html
{% extends 'layout.html' %}

{% block content %}
<div class="container">
    <div style="margin-bottom: 10px" class="clearfix">
        <a class="btn btn-success" href="/pretty/add/" target="_blank">
            <span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
            新建靓号
        </a>

        <div style="float: right;width: 300px;">
            <form method="get">
                <div class="input-group">
                    <input type="text" name="q" class="form-control" placeholder="Search for..."
                           value="{{ search_data }}">
                    <span class="input-group-btn">
                        <button class="btn btn-default" type="submit">
                            <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
                        </button>
                    </span>
                </div>
            </form>
        </div>
    </div>

    <div class="panel panel-default">
        <!-- Default panel contents -->
        <div class="panel-heading">
            <span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
            靓号列表
        </div>

        <!-- Table -->
        <table class="table table-bordered">
            <thead>
            <tr>
                <th>ID</th>
                <th>号码</th>
                <th>价格</th>
                <th>级别</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            {% for obj in queryset %}
            <tr>
                <th>{{ obj.id }}</th>
                <td>{{ obj.mobile }}</td>
                <td>{{ obj.price }}</td>
                <td>{{ obj.get_level_display }}</td>
                <td>{{ obj.get_status_display }}</td>
                <td>
                    <a class="btn btn-primary btn-xs" href="/pretty/{{ obj.id }}/edit/">编辑</a>
                    <a class="btn btn-danger btn-xs" href="/pretty/{{ obj.id }}/delete/">删除</a>
                </td>
            </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>

    <ul class="pagination">
        {{ page_string }}
    </ul>
    <br/>
    <form method="get">
        <div class="input-group" style="width: 200px">
            <input type="text" name="page" class="form-control" placeholder="页码">
            <span class="input-group-btn">
                <button class="btn btn-default" type="button">跳转</button>
            </span>
        </div>
    </form>
</div>
{% endblock %}

上一篇:使用 bend-ingest-kafka 将数据流实时导入到 Databend


下一篇:使用React复刻ThreeJS官网示例——keyframes动画