Django开发3

各位小伙伴想要博客相关资料的话关注公众号:chuanyeTry即可领取相关资料!

Django开发

  • 部门管理
  • 用户管理
  • 用户列表
  • 新建用户
     - ModelForm,针对数据库中的某个表。
     - Form
    

编辑用户

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

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

  • 提交:

    • 错误提示

    • 数据校验

    • 在数据库更新

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

9.靓号管理

9.1 表结构

在这里插入图片描述

根据表结构的需求,在models.py中创建类(由类生成数据库中的表)。

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)

自己在数据模拟创建一些数据:

insert into app01_prettynum(mobile,price,level,status)values("111111111",19,1,1);
mysql> select * from app01_prettynum;
+----+-----------+-------+-------+--------+
| id | mobile    | price | level | status |
+----+-----------+-------+-------+--------+
|  1 | 111111111 |    19 |     1 |      1 |
|  2 | 111111111 |    19 |     1 |      1 |
|  3 | 111111111 |    19 |     1 |      1 |
|  4 | 111111111 |    19 |     1 |      1 |
+----+-----------+-------+-------+--------+
4 rows in set (0.01 sec)

9.2 靓号列表

  • URL

  • 函数

    • 获取所有的靓号

    • 结合html+render将靓号罗列出来

      id	号码	价格	级别(中文)	状态(中文)
      

9.3 新建靓号

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

  • URL

  • ModelForm类

    from django import forms
    
    class PrettyModelForm(forms.ModelForm):
    	...
    
  • 函数

    • 实例化类的对象
    • 通过render将对象传入到HTML中。
    • 模板的循环展示所有的字段。
  • 点击提交

    • 数据校验
    • 保存到数据库
    • 跳转回靓号列表

在这里插入图片描述

9.4 编辑靓号

  • 列表页面:/pretty/数字/edit/
  • URL
  • 函数
    • 根据ID获取当前编辑的对象
    • ModelForm配合,默认显示数据。
    • 提交修改。

在这里插入图片描述

不允许手机号重复。

  • 添加:【正则表达式】【手机号不能存在】

    # [obj,obj,obj]
    queryset = models.PrettyNum.objects.filter(mobile="1888888888")
    
    obj = models.PrettyNum.objects.filter(mobile="1888888888").first()
    
    # True/False
    exists = models.PrettyNum.objects.filter(mobile="1888888888").exists()
    
  • 编辑:【正则表达式】【手机号不能存在】

    排除自己以外,其他的数据是否手机号是否重复?
    
    # id!=2 and mobile='1888888888'
    models.PrettyNum.objects.filter(mobile="1888888888").exclude(id=2)
    

9.5 搜索手机号

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

data_dict = {"mobile":"19999999991","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

data_dict = {"id__lte":12}
models.PrettyNum.objects.filter(**data_dict)
models.PrettyNum.objects.filter(mobile="999")               # 等于
models.PrettyNum.objects.filter(mobile__startswith="1999")  # 筛选出以1999开头
models.PrettyNum.objects.filter(mobile__endswith="999")     # 筛选出以999结尾
models.PrettyNum.objects.filter(mobile__contains="999")     # 筛选出包含999

data_dict = {"mobile__contains":"999"}
models.PrettyNum.objects.filter(**data_dict)

9.6 分页

queryset = models.PrettyNum.objects.all()
//取所有
queryset = models.PrettyNum.objects.filter(id=1)[0:10]
//取前十条

# 第1页
queryset = models.PrettyNum.objects.all()[0:10]

# 第2页
queryset = models.PrettyNum.objects.all()[10:20]

# 第3页
queryset = models.PrettyNum.objects.all()[20:30]
data = models.PrettyNum.objects.all().count()
data = models.PrettyNum.objects.filter(id=1).count()
  • 分页的逻辑和处理规则

  • 封装分页类

    • 从头到尾开发
    • 写项目用【pagination.py】公共组件。
  • 小Bug,搜索 + 分页情况下。

    分页时候,保留原来的搜索条件
    
    http://127.0.0.1:8000/pretty/list/?q=888
    http://127.0.0.1:8000/pretty/list/?page=1
    
    http://127.0.0.1:8000/pretty/list/?q=888&page=23
    

10.时间插件

<link rel="stylesheet" href="static/plugins/bootstrap-3.4.1/css/bootstrap.css">
<link rel="stylesheet" href="static/plugins/bootstrap-datepicker/css/bootstrap-datepicker.css">


<input type="text" id="dt" class="form-control" placeholder="入职日期">



<script src="static/js/jquery-3.6.0.min.js"></script>
<script src="static/plugins/bootstrap-3.4.1/js/bootstrap.js"></script>
<script src="static/plugins/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
<script src="static/plugins/bootstrap-datepicker/locales/bootstrap-datepicker.zh-CN.min.js"></script>


<script>
    $(function () {
        $('#dt').datepicker({
            format: 'yyyy-mm-dd',
            startDate: '0',
            language: "zh-CN",
            autoclose: true
        });

    })
</script>

11.ModelForm和BootStrap

  • ModelForm可以帮助我们生成HTML标签。

    class UserModelForm(forms.ModelForm):
        class Meta:
            model = models.UserInfo
            fields = ["name", "password",]
    
    form = UserModelForm()
    
    {{form.name}}      普通的input框
    {{form.password}}  普通的input框
    
  • 定义插件

    class UserModelForm(forms.ModelForm):
        class Meta:
            model = models.UserInfo
            fields = ["name", "password",]
            widgets = {
                "name": forms.TextInput(attrs={"class": "form-control"}),
                "password": forms.PasswordInput(attrs={"class": "form-control"}),
                "age": forms.TextInput(attrs={"class": "form-control"}),
            }
    
    
    class UserModelForm(forms.ModelForm):
        name = forms.CharField(
            min_length=3,
            label="用户名",
            widget=forms.TextInput(attrs={"class": "form-control"})
        )
    
        class Meta:
            model = models.UserInfo
            fields = ["name", "password", "age"]
    
    {{form.name}}      BootStrap的input框
    {{form.password}}  BootStrap的input框
    
  • 重新定义的init方法,批量设置

    class UserModelForm(forms.ModelForm):
        class Meta:
            model = models.UserInfo
            fields = ["name", "password", "age",]
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            
            # 循环ModelForm中的所有字段,给每个字段的插件设置
            for name, field in self.fields.items():
    			field.widget.attrs = {
                    "class": "form-control", 
                    "placeholder": field.label
                }
    
    class UserModelForm(forms.ModelForm):
        class Meta:
            model = models.UserInfo
            fields = ["name", "password", "age",]
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            
            # 循环ModelForm中的所有字段,给每个字段的插件设置
            for name, field in self.fields.items():
                # 字段中有属性,保留原来的属性,没有属性,才增加。
                if field.widget.attrs:
    				field.widget.attrs["class"] = "form-control"
    				field.widget.attrs["placeholder"] = field.label
                else:
                    field.widget.attrs = {
                        "class": "form-control", 
                        "placeholder": field.label
                    }
    
    class UserEditModelForm(forms.ModelForm):
        class Meta:
            model = models.UserInfo
            fields = ["name", "password", "age",]
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            
            # 循环ModelForm中的所有字段,给每个字段的插件设置
            for name, field in self.fields.items():
                # 字段中有属性,保留原来的属性,没有属性,才增加。
                if field.widget.attrs:
    				field.widget.attrs["class"] = "form-control"
    				field.widget.attrs["placeholder"] = field.label
                else:
                    field.widget.attrs = {
                        "class": "form-control", 
                        "placeholder": field.label
                    }
    
  • 自定义类

    class BootStrapModelForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            # 循环ModelForm中的所有字段,给每个字段的插件设置
            for name, field in self.fields.items():
                # 字段中有属性,保留原来的属性,没有属性,才增加。
                if field.widget.attrs:
    				field.widget.attrs["class"] = "form-control"
    				field.widget.attrs["placeholder"] = field.label
                else:
                    field.widget.attrs = {
                        "class": "form-control", 
                        "placeholder": field.label
                    }
    
    class UserEditModelForm(BootStrapModelForm):
        class Meta:
            model = models.UserInfo
            fields = ["name", "password", "age",]
    

models表不能拆分,
view表可以拆分

操作

  • 提取公共的类

    在这里插入图片描述

    在这里插入图片描述

  • ModelForm拆分出来
    在这里插入图片描述

  • 视图函数的归类
    在这里插入图片描述
    在这里插入图片描述

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值