首页 > 其他分享 >08-项目实战-手机号管理

08-项目实战-手机号管理

时间:2023-02-01 11:58:26浏览次数:44  
标签:实战 手机号 form models 08 request phone data

# 1. 依赖工具类 bootstrap.py  -bootstrap
# 2. 依赖工具类 pagemtion.py -分页

1. 创建手机号表

# app-->models.py

from django.db import models
class Phone(models.Model):
    """用户手机号"""
    phone = models.CharField(verbose_name="手机号", max_length=64)
    # 想要允许为空,null=True,blank=True;  default:默认值
    number = models.IntegerField(verbose_name="登陆次数", default=0)

    level_choices = (
        (1, "用户"),
        (2, "超级管理员")
    )
    level = models.SmallIntegerField(verbose_name="类别", choices=level_choices, default=1)

    status_choices = (
        (1, "正常"),
        (2, "异常")
    )
    status = models.SmallIntegerField(verbose_name="状态", choices=status_choices, default=1)

# python manage.py makemigrations
# python manage.py migrate

2. 创建路由(url)

# 项目-->urls.py
# 手机号管理
from bbc_list.views import login, home_page, order, phone
urlpatterns = [
    path("phone/list/", phone.phone_list),
    path("phone/add/", phone.phone_add),
    path("phone/<int:nid>/update/", phone.phone_update),
    path("phone/<int:nid>/delete/", phone.phone_delete),]

3. 将ModelForm封装到其他文件

# app-->utils-->form.py

from django import forms
from bbc_list import models
from bbc_list.utils.bootstrap import BootStrapModelForm

class PhoneModelForm(BootStrapModelForm):
    """新增"""
    # 进行格式的效验,第一种:字段+正则
    from django.core.validators import RegexValidator
    phone = forms.CharField(label="手机号",
                            validators=[RegexValidator(r'1[3-9]\d{9}$', '手机号格式错误'), ],
                            )  # 使用正则效验,不符合提示错误信息

    #
    class Meta:
        model = models.Phone
        fields = ['phone', 'number', 'level', 'status']
        # fields = "__all__"  # 所有字段
        # exclude = ["level"]  # 排除那个字段

    # 第二种效验:钩子方法,clean_字段名
    def clean_phone(self):
        from django.core.validators import ValidationError
        txt = self.cleaned_data["phone"]  # self.cleaned_data["字段"]:获取用户传入的数据
        exists = models.Phone.objects.filter(phone=txt).exists()  # .exists() : 判断用户输入的手机号是否已存在

        # 验证不通过抛给前端一个异常
        if exists:
            raise ValidationError("手机号已存在")  # 返回前端异常信息

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


class PhoneUpdateModelForm(BootStrapModelForm):
    """修改"""
    # phone= forms.CharField(disabled=True, label="手机号")  # 设置不可更改

    from django.core.validators import RegexValidator
    phone = forms.CharField(
        label="手机号",
        validators=[RegexValidator(r'1[3-9]\d{9}$', "手机号格式错误")]
    )

    class Meta:
        model = models.Phone
        fields = ['phone', 'number', 'level', 'status']  # 只显示里面有的数据

    # 效验第二种: 钩子方法 clean_字段名
    def clean_phone(self):
        from django.core.validators import ValidationError

        # 当前编辑的哪一行ID
        print("instance.pk==", self.instance.pk)  # 固定语法:instance:对象;pk:id

        txt = self.cleaned_data["phone"]  # 获取用户传入的数据
        exists = models.Phone.objects.exclude(id=self.instance.pk).filter(phone=txt).exists()  # 排除自己,判断用户输入的手机号是否已存在
        # 验证不通过,抛给前端一个异常
        if exists:
            raise ValidationError("手机号已存在")  # 返回前端异常信息

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

4. 编写视图函数

# app-->views-->phone.py

from django.shortcuts import render, redirect

from bbc_list import models
from bbc_list.utils.form import PhoneModelForm, PhoneUpdateModelForm


def phone_list(request):
    """手机号列表"""

    data_dict = {}
    search_data = request.GET.get("q", "")  # 搜索: 有值的话拿值,没值空字符串
    # print("search_data===", search_data)
    if search_data:
        data_dict["phone__contains"] = search_data  # mobile__contains: 手机号__模糊搜索

    # 导入分页
    from bbc_list.utils.pagemtion import Pagination
    # select * from 表 order by level desc;  django里直接输入表字段正序; -字段:倒叙;
    queryset = models.Phone.objects.filter(**data_dict).order_by("-level")

    page_object = Pagination(request, queryset)
    context = {
        "search_data": search_data,

        "phone": page_object.page_queryset,  # 分完页的所有数据
        "page_string": page_object.html()  # 页码

    }

    return render(request, "phone_list.html", context)


def phone_add(request):
    """添加手机号"""
    if request.method == "GET":
        form = PhoneModelForm()

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

    form = PhoneModelForm(data=request.POST)
    if form.is_valid():
        form.save()
        return redirect("/phone/list/")

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


def phone_update(request, nid):
    """修改手机号"""
    row_object = models.Phone.objects.filter(id=nid).first()
    if request.method == "GET":
        form = PhoneUpdateModelForm(instance=row_object)  # 传入数据库对象,用于在界面展示原有数据
        return render(request, "phone_update.html", {"form": form})

    form = PhoneUpdateModelForm(data=request.POST, instance=row_object)

    if form.is_valid():
        form.save()
        return redirect("/phone/list/")

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


def phone_delete(request, nid):
    """删除手机号"""
    models.Phone.objects.filter(id=nid).delete()
    return redirect("/phone/list/")


5. 编写html页面

# phone_list.html

{% extends 'one.html' %}

{% block content %}
<div class="container">
    <div style="margin-bottom:10px;" class="clearfix">
        <a class="btn btn-success" href="/phone/add/">
            <span class="glyphicon glyphicon-plus" aria-hidden="true">
                新建手机号</span></a>

        <div style="float:right;width:300px;">
            <form method="post">
                {% csrf_token %}
                <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>

        <a class="btn btn-success" href="/phone/add/">
            <span class="glyphicon glyphicon-plus" aria-hidden="true">
                新建手机号ModelForm</span></a>
    </div>
    <div class="panel panel-default">
        <div class="panel-heading">
            <span class="glyphicon glyphicon-th-list" aria-hidden="true">
                手机号列表
            </span>
        </div>

        <table class="table table-bordered">
            <thead>
            <tr>
                <th>ID</th>
                <th>手机号</th>
                <th>登陆次数</th>
                <th>类别</th>
                <th>状态</th>
            </tr>
            </thead>
            <tbody>
            {% for obj in phone %}
            <tr>
                <th>{{ obj.id }}</th>
                <th>{{ obj.phone }}</th>
                <th>{{ obj.number }}</th>
                <!-- {{ obj.get_表字段_display }}获取定义的限制文字  -->
                <td>{{ obj.get_level_display }}</td>
                <td>{{ obj.get_status_display }}</td>
                <td>
                    <a class="btn btn-primary btn-xs" href="/phone/{{ obj.id }}/update/">编辑</a>
                    <a class="btn btn-danger btn-xs" href="/phone/{{ obj.id }}/delete/">删除</a>
                </td>
            </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>
    <div class="clearfix">
        <ul class="pagination">
            {{ page_string }}
        </ul>
    </div>

</div>


{% endblock %}
# phone_add.html
{% extends 'one.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">
            <!--            novalidate: 关掉浏览器的校验-->
            <form method="post" novalidate>
                {% csrf_token %}

                {% for field in form %}
                <div class="form-group">
                    <label>{{ field.label }}</label>
                    <!--                    <input type="text" class="form-control" placeholder="姓名" name="user">-->
                    {{ field }}
                    <span style="color:red;"> {{ field.errors.0 }}</span>
                </div>
                {% endfor %}

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

{% endblock %}


# phone_update.html
{% extends 'one.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">
<!--            novalidate: 关掉浏览器的校验-->
            <form method="post" novalidate>
                {% csrf_token %}

                {% for field in form %}
                <div class="form-group">
                    <label>{{ field.label }}</label>
<!--                    <input type="text" class="form-control" placeholder="姓名" name="user">-->
                    {{ field }}
                    <span style="color:red;">
                    {{ field.errors.0 }}
                        </span>
                </div>
                {% endfor %}

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


{% endblock %}

标签:实战,手机号,form,models,08,request,phone,data
From: https://www.cnblogs.com/kh-1314/p/17044051.html

相关文章

  • 18-项目实战-日志输出及打印--logging
    转载:https://www.cnblogs.com/wangyingblock/p/10407987.htmlDjango日志输出及打印--loggingDjango使用python自带的logging作为日志打印工具。logging是线程安全的......
  • 17-项目实战-上传excel并保存到数据库
    1.创建数据表classHome(models.Model):"""首页"""title=models.CharField(verbose_name="标题",max_length=32)def__str__(self):return......
  • 16-项目实战-上传文件-实战
    1.创建数据表classUserInfo(models.Model):"""用户信息"""name=models.CharField(verbose_name="姓名",max_length=32)age=models.IntegerField(ve......
  • 15-项目实战-上传文件-配置media
    #在django的开发过程中有两个特殊的文件夹:static:存放静态文件的路径,包括:CSS,JS,项目图片.media:用户上传的数据.1.配置media#启用media:在根目录......
  • 14-项目实战-图形页面
    #第三方js插件1.highchart国外:https://www.hcharts.cn/demo/highcharts/column-basic2.echats国内(推荐):https://echarts.apache.org/handbook/zh/g......
  • 13-项目实战-订单管理
    #1.依赖bootstrap.py-ModelForm#2.依赖pagemtion.py-分页1.创建订单管理表classBill(models.Model):"""订单管理"""oid=models.CharField(verbos......
  • 08-SO加载解析过程
    1JAVA层函数调用关系本文通过分析Android 4.4版本的源码,了解linker是如何加载并链接SO文件。在阅读本文之前,读者最好阅读有关ELF的文件格式,可以阅读《ELF文件结构学习》......
  • 弱网测试利器-Charles工具实战
    每天进步一点点,关注我们哦,每天分享测试技术文章本文章出自【码同学软件测试】码同学公众号:自动化软件测试,领取资料可加:magetest码同学抖音号:小码哥聊软件测试一:弱网测......
  • OKR之剑·实战篇04:OKR执行过程优化的那些关键事
    作者:vivo互联网平台产品研发团队本文是《OKR之剑》系列之实战第4篇——OKR执行过程不是一成不变的,团队和个人在执行中不断优化执行的具体行动,保障OKR的高效执行。......
  • 极客时间 Java并发编程实战 笔记
    思考、再思考、总结、再总结01可见性、原子性和有序性举几个例子先。缓存可能导致可见性问题,因为多核CPU上的多个核可能都持有同一数据的不同缓存。两个线程并行地对......