目录
0、新建Django项目
(1)修改setting.py
(2)删除根目录下的templates
(3)创建App
(4)注册App
(5)创建App->templates
(6)引入static静态文件
(7)安装mysql第三方库
(8)打开mysql client 创建新的数据库
(9)修改setting.py配置
1、创建数据表结构
2、生成数据表
3、在数据库插入几条测试数据
4、创建号码列表页面
5、实现添加功能
6、实现编辑功能
7、实现删除功能
8、实现搜索功能
?用户需求:
表结构:
id-号码id
mobile-手机号
price-号码价格
level-号码等级(用元组的方式进行选择:低:1,中:2,高:3)
status-号码状态(1-占用,2-未占用)
---------------------------------------------------------------------------------------------------------------------------------
项目开发:
0、新建Django项目
(1)修改setting.py
(2)删除根目录下的templates
(3)创建App
(4)注册App
setting.py
(5)创建App->templates
(6)引入static静态文件
(7)安装mysql第三方库
方法前面已经说过了。
?
(8)打开mysql client 创建新的数据库
create database Mobile_Nums default charset=utf8;
(9)修改setting.py配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mobile_nums',
'USER': 'root',
'PASSWORD': '123456',
'HOST': '127.0.0.1',
'PORT': '3306',
}
}
1、创建数据表结构
from django.db import models
# Create your models here.
class PrettyNum(models.Model):
"""靓号表"""
mobile = models.CharField(verbose_name="手机号",max_length=32)
price = models.IntegerField(verbose_name="价格",default=0)#默认为空:,null=True,blank=True
level_choices = (
(1, "1级"),
(2, "2级"),
(3, "3级"),
(4, "4级"),
)
level = models.SmallIntegerField(verbose_name="级别",choices=level_choices,default=1)#默认级别为1
status_chioces =(
(1, "已占用"),
(0, "未占用"),
)
status = models.SmallIntegerField(verbose_name="状态",choices=status_chioces,default=0)
2、生成数据表
??
3、在数据库插入几条测试数据
insert into app01_prettynum(mobile,price,level,status)values("138521112222",10000,2,0);
?
?4、创建号码列表页面
创建url
path('pretty/list/',views.pretty_list)
创建视图函数
from django.shortcuts import render
from app01 import models
# Create your views here.
def pretty_list(request):
"""靓号列表"""
#获取的列表按等级降序排列
#select * from 表 order by level desc;
qureyset = models.PrettyNum.objects.all().order_by("-level")
return render(request,"pretty_list.html",{"qureyset":qureyset})
创建导航页面模板
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>
{% block title_content %}
{% endblock %}
</title>
<link rel="stylesheet" href="{% static 'plugins/bootstrap-3.4.1/css/bootstrap.min.css' %}">
</head>
<body>
<!--导航-->
<div class="bs-example" data-example-id="inverted-navbar">
<nav class="navbar navbar-inverse">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse"
data-target="#bs-example-navbar-collapse-9" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">靓号管理系统</a>
</div>
<!--搜索-->
<form class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" placeholder="输入号码">
</div>
<button type="submit" class="btn btn-default">搜索</button>
</form>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-9">
<ul class="nav navbar-nav">
<li><a href="/pretty/list/">靓号管理</a></li>
<li><a href="/pretty/add/">添加靓号</a></li>
<li><a href="#">Link</a></li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="#">登录</a></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true"
aria-expanded="false">代码骑士 <span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" class="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
</div>
{% block content %}{% endblock %}
<script src="{% static 'js/jquery-3.6.0.min.js' %}"></script>
<script src="{% static 'plugins/bootstrap-3.4.1/js/bootstrap.min.js' %}"></script>
</body>
</html>
模板页面
创建列表页面
{% extends 'template.html' %}
{% block title_content %}
靓号列表
{% endblock %}
{% block content %}
<div class="container">
<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>
<th>ID</th>
<th>号码</th>
<th>价格</th>
<th>级别</th>
<th>状态</th>
<th>操作</th>
</thead>
<tbody>
{% for qurey in qureyset %}
<tr>
<th>{{ qurey.id }}</th>
<td>{{ qurey.mobile }}</td>
<td>{{ qurey.price }}</td>
<td>{{ qurey.get_level_display }}</td>
<td>{{ qurey.get_status_display }}</td>
<td>
<a class="btn btn-primary btn-xs" href="#">编辑</a>
<a class="btn btn-danger btn-xs" href="#">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}
访问页面
5、实现添加功能
urls.py
path('pretty/add/', views.pretty_add),
?views.py
from django.shortcuts import render,redirect
from app01 import models
from django import forms
# 验证方式1:引入对模型的正则表达式
from django.core.validators import RegexValidator
#验证方式2
from django.core.exceptions import ValidationError
class PrettyModelForm(forms.ModelForm):
# 使用bootstrap样式
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}
# #验证方式1:正则表达式
# mobile = forms.CharField(
# label="手机号",
# validators=[RegexValidator(r'[3-9]\d{9}$','手机号格式错误')],#\d{11}#1[3-9]\d{9}$
# )
#获取模板元包
class Meta:
model = models.PrettyNum
#获取字段
#fields = "__all__"#获取全部字段
#exclude = ["level"]#反选指定字段
fields = ["mobile", "price", "level", "status"] # 获取指定字段
# 验证方式2:钩子函数
def clean_mobile(self):
txt_mobile = self.cleaned_data["mobile"]
if len(txt_mobile)!=11:
raise ValidationError("位数少于11位")
return txt_mobile
def pretty_list(request):
"""靓号列表"""
#获取的列表按等级降序排列
#select * from 表 order by level desc;
qureyset = models.PrettyNum.objects.all().order_by("-level")
return render(request,"pretty_list.html",{"qureyset":qureyset})
def pretty_add(request):
"""添加靓号"""
if request.method == "GET":
form = PrettyModelForm()
return render(request,'pretty_add.html',{"form":form})
form = PrettyModelForm(data=request.POST)
if form.is_valid(): # 校验成功
form.save()
return redirect("/pretty/list/")
return render(request, 'pretty_add.html', {'form': form})
数据库表单模板类
class PrettyModelForm(forms.ModelForm):
# 使用bootstrap样式
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}
# #验证方式1:正则表达式
# mobile = forms.CharField(
# label="手机号",
# validators=[RegexValidator(r'[3-9]\d{9}$','手机号格式错误')],#\d{11}#1[3-9]\d{9}$
# )
#获取模板元包
class Meta:
model = models.PrettyNum
#获取字段
#fields = "__all__"#获取全部字段
#exclude = ["level"]#反选指定字段
fields = ["mobile", "price", "level", "status"] # 获取指定字段
# 验证方式2:钩子函数
def clean_mobile(self):
txt_mobile = self.cleaned_data["mobile"]
if len(txt_mobile)!=11:
raise ValidationError("位数少于11位")
return txt_mobile
两种校验方法
字段+正则
from django.core.validators import RegexValidator
# #验证方式1:正则表达式
# mobile = forms.CharField(
# label="手机号",
# validators=[RegexValidator(r'[3-9]\d{9}$','手机号格式错误')],#\d{11}#1[3-9]\d{9}$
# )
?钩子函数
def clean_mobile(self):
txt_mobile = self.cleaned_data["mobile"]
if len(txt_mobile)!=11:
raise ValidationError("位数少于11位")
return txt_mobile
pretty_add.html
{% extends 'template.html' %}
{% block content %}
<div>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"> 新建靓号 </h3>
</div>
<div class="panel-body">
<!--表单-->
<!--action可以不写,因为不写的话提交的是当前地址-->
<form method="post" novalidate><!--novalidate:表示不采用views函数里的校验,采用自己写的页面校验-->
{% csrf_token %}
{% for obj in form %}
<div class="form-group">
<label> {{ obj.label }} </label>
{{ obj }}
<span style="color:red"> {{ obj.errors.0 }}</span><!--错误信息以列表形式存储-->
<!--<input type="text" class="form-control" placeholder="姓名" name="name"/>-->
</div>
{% endfor %}
<button type="submit" class="btn btn-primary"> 提交</button>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
setting.py
设置中文
页面访问:
6、实现编辑功能
?urls.py
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
path('pretty/list/', views.pretty_list),
path('pretty/add/', views.pretty_add),
path('pretty/<int:nid>/edit/', views.pretty_edit),
]
views.py
?
from django.shortcuts import render,redirect
from app01 import models
from django import forms
# 验证方式1:引入对模型的正则表达式
from django.core.validators import RegexValidator
#验证方式2
from django.core.exceptions import ValidationError
class PrettyModelForm(forms.ModelForm):
# 使用bootstrap样式
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}
#验证方式1:正则表达式
# mobile = forms.CharField(
# label="手机号",
# validators=[RegexValidator(r'[3-9]\d{9}$','手机号格式错误')],#\d{11}#1[3-9]\d{9}$
# )
#获取模板元包
class Meta:
model = models.PrettyNum
#获取字段
#fields = "__all__"#获取全部字段
#exclude = ["level"]#反选指定字段
fields = ["mobile", "price", "level", "status"] # 获取指定字段
# 验证方式2:钩子函数
def clean_mobile(self):
txt_mobile = self.cleaned_data["mobile"]
#验证手机号是否已存在
exists = models.PrettyNum.objects.filter(mobile=txt_mobile).exists()
if exists:
raise ValidationError("手机号已存在")
elif len(txt_mobile)!=11:
raise ValidationError("手机号格式错误")
return txt_mobile
class PrettyEditModelForm(forms.ModelForm):
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}
mobile = forms.CharField(disabled=True,label="手机号")
# 验证方式1:正则表达式
mobile = forms.CharField(
label="手机号",
validators=[RegexValidator(r'[3-9]\d{9}$', '手机号格式错误')], # \d{11}#1[3-9]\d{9}$
)
class Meta:
model = models.PrettyNum
fields = ["mobile", "price", "level", "status"]
def clean_mobile(self):
#当前编辑的那一行主键(id)
#print(self.instance.pk)
txt_mobile = self.cleaned_data["mobile"]
#验证手机号是否已存在(排除自身)
exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists()
if exists:
raise ValidationError("手机号已存在")
elif len(txt_mobile)!=11:
raise ValidationError("手机号格式错误")
return txt_mobile
def pretty_list(request):
"""靓号列表"""
#获取的列表按等级降序排列
#select * from 表 order by level desc;
qureyset = models.PrettyNum.objects.all().order_by("-level")
return render(request,"pretty_list.html",{"qureyset":qureyset})
def pretty_add(request):
"""添加靓号"""
if request.method == "GET":
form = PrettyModelForm()
return render(request,'pretty_add.html',{"form":form})
form = PrettyModelForm(data=request.POST)
if form.is_valid(): # 校验成功
form.save()
return redirect("/pretty/list/")
return render(request, 'pretty_add.html', {'form': form})
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})
# 处理post请求
form = PrettyEditModelForm(data=request.POST, instance=row_object)
# 校验
if form.is_valid():
form.save()
return redirect("/pretty/list/")
return render(request, 'pretty_edit.html', {"form": form})
pretty.html
{% extends 'template.html' %}
{% block content %}
<div>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"> 编辑靓号 </h3>
</div>
<div class="panel-body">
<!--表单-->
<!--action可以不写,因为不写的话提交的是当前地址-->
<form method="post" novalidate><!--novalidate:表示不采用views函数里的校验,采用自己写的页面校验-->
{% csrf_token %}
{% for obj in form %}
<div class="form-group">
<label> {{ obj.label }} </label>
{{ obj }}
<span style="color:red"> {{ obj.errors.0 }}</span><!--错误信息以列表形式存储-->
<!--<input type="text" class="form-control" placeholder="姓名" name="name"/>-->
</div>
{% endfor %}
<button type="submit" class="btn btn-primary"> 提交</button>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
?页面访问:
?
7、实现删除功能
urls.py
path('pretty/delete/', views.pretty_delete),
views.py
def pretty_delete(request):
"""删除靓号"""
nid = request.GET.get("nid")
models.PrettyNum.objects.filter(id=nid).delete()
return redirect("/pretty/list/")
pretty_list.html?
{% extends 'template.html' %}
{% block title_content %}
靓号列表
{% endblock %}
{% block content %}
<div class="container">
<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>
<th>ID</th>
<th>号码</th>
<th>价格</th>
<th>级别</th>
<th>状态</th>
<th>操作</th>
</thead>
<tbody>
{% for qurey in qureyset %}
<tr>
<th>{{ qurey.id }}</th>
<td>{{ qurey.mobile }}</td>
<td>{{ qurey.price }}</td>
<td>{{ qurey.get_level_display }}</td>
<td>{{ qurey.get_status_display }}</td>
<td>
<a class="btn btn-primary btn-xs" href="/pretty/{{ qurey.id }}/edit">编辑</a>
<a class="btn btn-danger btn-xs" href="/pretty/delete/?nid={{ qurey.id }}">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}
8、实现搜索功能
两种方法:1、直接搜 2、使用字典搜
对于数字的搜索
?对于字符串的搜索
修改模板:
?template.html
<!--搜索-->
<form class="navbar-form navbar-left" method="get" action="/pretty/list/">
<div class="form-group">
<input type="text" class="form-control" placeholder="输入号码" name="q" value="{{ value }}">
</div>
<button type="submit" class="btn btn-default">搜索</button>
</form>
?views.py
def pretty_list(request):
"""靓号列表"""
#搜索字典
data_dict={}
value = request.GET.get("q","")
if value:
data_dict["mobile__contains"]=value
#获取的列表按等级降序排列
#select * from 表 order by level desc;
#qureyset = models.PrettyNum.objects.all().order_by("-level")
qureyset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")
return render(request, "pretty_list.html", {"qureyset": qureyset,"value":value})
|