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 = UserInfofields = ["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.UserInfofields = ["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":#     continuefield.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.UserInfofields = ["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":#     continuefield.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=Trueprice = 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 formsclass PrettyModelForm(forms.ModelForm):...

函数

--实例化类的对象

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

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

点击提交

--数据校验

--保存到数据库

--跳转回靓号列表

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

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

from django.core.validators import RegexValidator
from django.core.exceptions import ValidationErrorclass 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":#     continuefield.widget.attrs = {"class": "form-control", "placeholder": field.label}# 验证:方式2def 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 RegexValidatorclass 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":#     continuefield.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, redirectfrom 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.UserInfofields = ["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":#     continuefield.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 ValidationErrorclass PrettyModelForm(forms.ModelForm):# 验证:方式1mobile = 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":#     continuefield.widget.attrs = {"class": "form-control", "placeholder": field.label}# 验证:方式2def clean_mobile(self):txt_mobile = self.cleaned_data["mobile"]exists = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()if exists:raise ValidationError("手机号已存在")# 验证通过,用户输入的值返回return txt_mobiledef 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.PrettyNumfields = ["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}# 验证:方式2def 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_mobiledef 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, redirectfrom 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.UserInfofields = ["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":#     continuefield.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 = 10start = (page - 1) * page_sizeend = 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 = 5if total_page_count <= 2 * plus + 1:# 数据库中的数据比较少,都没有达到11页start_page = 1end_page = total_page_count + 1else:# 当前页<5时if page <= plus:start_page = 1end_page = 2 * plus + 1else:if (page + plus) > total_page_count:start_page = total_page_count - 2 * plusend_page = total_page_countelse:# 数据库中的数据比较多>11页start_page = page - plusend_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 ValidationErrorclass PrettyModelForm(forms.ModelForm):# 验证:方式1mobile = 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":#     continuefield.widget.attrs = {"class": "form-control", "placeholder": field.label}# 验证:方式2def clean_mobile(self):txt_mobile = self.cleaned_data["mobile"]exists = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()if exists:raise ValidationError("手机号已存在")# 验证通过,用户输入的值返回return txt_mobiledef 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.PrettyNumfields = ["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}# 验证:方式2def 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_mobiledef 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 %}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/40056.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

一键获取:Win11笔记本系统下载地址!

在笔记本电脑操作中&#xff0c;用户想安装一款适合笔记本电脑使用的Win11系统&#xff0c;但不知道在哪里可以下载到&#xff1f;接下来系统之家小编给大家分享Win11笔记本系统下载地址&#xff0c;有需要的小伙伴一键点击即可获取&#xff0c;快速安装系统&#xff0c;即可体…

<电力行业> - 《第15课:电力领域(一)》

1 电网 发电厂与最终用电用户&#xff08;负荷&#xff09;往往相距很远&#xff0c;因此电力需要由电厂”输送“到最终用户&#xff0c;即“输电环节“&#xff0c;电流的输送往往导致因线路发热造成损耗&#xff0c;所以在输送的时候都是通过变电升高电压&#xff0c;让电流…

计算机网络 | 期末复习

物理层&#xff1a; 奈氏准则&#xff1a;带宽&#xff08;w Hz&#xff09;&#xff0c;在不考虑噪音的情况下&#xff0c;最大速率&#xff08;2W&#xff09;码元/秒 信噪比S/N&#xff1a;以分贝&#xff08;dB&#xff09;为度量单位。信噪比&#xff08;dB&#xff09;…

C++初学者指南-3.自定义类型(第一部分)-异常

C初学者指南-3.自定义类型(第一部分)-异常 文章目录 C初学者指南-3.自定义类型(第一部分)-异常简介什么是异常&#xff1f;第一个示例用途:报告违反规则的行为异常的替代方案标准库异常处理 问题和保证资源泄露使用 RAII 避免内存泄漏&#xff01;析构函数&#xff1a;不要让异…

SpringBoot源码阅读3-启动原理

SpringBootApplication public class DistApplication {public static void main(String[] args) {// 启动入口SpringApplication.run()SpringApplication.run(DistApplication.class, args);} }1、服务构建 这里"服务"指的是SpringApplication对象&#xff0c;服务…

2024年港澳台联考考生成绩数据分析来啦

分数线 出炉 2024年的港澳台联考正式出分&#xff01;根据考生成绩&#xff0c;全国联招划档线如下&#xff1a; 一、本科批次 &#xff08;一&#xff09;普通类院校&#xff08;专业&#xff09;&#xff1a;文史类365分、理工类390分&#xff08;部分院校执行高分线&#…

持续直击WCCI 2024:金耀初教授、台湾省台北分会等获殊荣 横滨夜景美不胜收

持续直击WCCI 2024&#xff1a;金耀初教授、台湾省台北分会等获殊荣&#xff01;横滨夜景美不胜收&#xff01; 会议之眼 快讯 会议介绍 IEEE WCCI&#xff08;World Congress on Computational Intelligence&#xff09;2024&#xff0c;即2024年IEEE世界计算智能大会&…

BAS(入侵与攻击模拟)正在替代红队测试?

之前经常会被用户问到&#xff0c;漏扫、渗透和红队红的区别是啥&#xff1f; 传统的漏扫、渗透和红蓝对抗&#xff0c;可以看到工具化的漏洞不可靠&#xff0c;人工的成本就高。怎么找到一个漏洞可信度又高&#xff0c;成本又低的&#xff0c;就诞生了BAS。 抛开漏扫&#xf…

umi项目中的一些趣事

前言 出于某些安全问题&#xff0c;需要把HTML中框架注入的umi版本信息去掉&#xff0c;那要怎么搞呢~ 方案 查找官方文档&#xff0c;没发现可以去掉注入信息的方法&#xff0c;但在一番折腾后&#x1f609;终究还是解决了~ 发现 版本信息是从这里注入的~ Object.define…

解决pip安装时的“SyntaxError: invalid syntax”错误

项目场景&#xff1a; 项目中有新的成员加入时&#xff0c;第一步就是安装开发环境&#xff0c;然而往往同样的机器、同样的配置&#xff0c;我们却总能遇到各种各样不同的问题。 今天分享一个简单的操作问题。 问题描述 项目用到pandas&#xff0c;安装pandas时遇到Syntax…

Java后端每日面试题(day2)

目录 Session和Cookie的关系Cookie与Session的区别JWT 由哪些部分组成&#xff1f;如何防止 JWT 被篡改&#xff1f;JWT 的特点 Session和Cookie的关系 Session和Cookie都可以用来实现跟踪用户状态&#xff0c;而二者是关系的&#xff1a;Session的实现依赖于Cookie。 Session…

【C语言】顺序表经典算法

本文介绍的是两道顺序表经典算法题目。 移除元素 &#xff08;来源&#xff1a;LeetCode&#xff09; 题目 分析 我们很容易想到的办法是去申请一个新的数组&#xff0c;遍历原数组不等于val就把它拿到新数组里。但是题目的要求是不使用额外空间&#xff0c;所以这种方法我们…

Python面向对象编程中的继承及其应用

目录 1. 继承的基本概念 2. 继承的语法 3. 继承的应用场景 4. 使用示例&#xff1a;汽车销售系统 5. 总结 继承是面向对象编程中的一个重要概念&#xff0c;它允许我们根据已有类创建新类&#xff0c;并继承已有类的属性和方法。在本文中&#xff0c;我们将学习Python中的…

Unity3D中,AI角色Rigidbody旋转导致的动画问题

在制作一些AI角色的时候&#xff0c;可能会运用到Rigidbody组件来使AI角色拥有一些相关的物理属性&#xff0c;但是AI角色在受到一些物理碰撞或者惯性等原因&#xff0c;会发生旋转导致动画出现意料外的错误&#xff0c;比如在由动转静的时候&#xff0c;可能会发生向前翻转等一…

卷积层里的填充和步幅

一、定义 1、对于卷积&#xff0c;我们另一个超参数是核的大小&#xff0c;通常使用的卷积核是33或者55&#xff0c;很少用偶数核 2、填充是为了让输出不变或者变大&#xff0c;是为了在输入不太大&#xff0c;又能使模型足够深的情况下使用 3、填充&#xff1a;在输入周围添…

【Java学习笔记】java图形界面编程

在前面的章节中&#xff0c;我们开发运行的应用程序都没有图形界面&#xff0c;但是很多应用软件&#xff0c;如Windows下的Office办公软件、扑克牌接龙游戏软件、企业进销存ERP系统等&#xff0c;都有很漂亮的图形界面。素以需要我们开发具有图形界面的软件。 Java图形界面编程…

Megatron-DeepSpeed与Megatron-LM在reduce grad上的差异

Megatron-DeepSpeed与Megatron-LM在reduce grad上的差异 一.Megatron-DeepSpeed 实现【deepspeed/runtime/engine.py】二.ModelLink 实现【ParamAndGradBuffer】1.ParamAndGradBuffer功能介绍2.实现原理A.分配一大块内存B.获取视图C.all_reduce grad 测试DP1,TP2,PP1,MBS1,zero…

【信即是功夫】人皆有良知在心中

良知就是做人、做事的准则&#xff0c;良知就是天理&#xff1b;实实在在地自信 每个人心中都有一个圣人&#xff0c;只因自己不能真的相信&#xff0c;把这个圣人埋没了 良知在每个人心中&#xff0c;无论你如何做&#xff0c;也无法泯灭它。即使身为盗贼的人&#xff0c;他…

WebStorm配置路径别名(jsconfig.json)

项目是 ViteVueTs 新建一个 jsconfig.json文件 {"compilerOptions": {"baseUrl": ".","paths": {"/*": ["./src/*"]}},"exclude": ["node_modules", "dist"] }然后在 vite.confi…

Sping源码(九)—— Bean的初始化(非懒加载)—mergeBeanDefinitionPostProcessor

序言 前几篇文章详细介绍了Spring中实例化Bean的各种方式&#xff0c;其中包括采用FactoryBean的方式创建对象、使用反射创建对象、自定义BeanFactoryPostProcessor以及构造器方式创建对象。 创建对象 这里再来简单回顾一下对象的创建&#xff0c;不知道大家有没有这样一个疑…