P39P40,靓号提交,两种校验方式
1.链接跳转,/pretty_add/
2.URL
3.ModelForm
4.函数
实例化对象
render传入数据
模板循环
5.点击提交
views.py
from django import forms
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
class PrettyModelForm(forms.ModelForm):
# 验证字段方式1:字段+正则表达式
# mobile = forms.CharField(
# label="手机号",
# # validators=[RegexValidator(r'^159[0-9]+$')]
# # validators=[RegexValidator(r'^1\d{10}$', "手机号格式错误")]
# validators=[RegexValidator(r'^1\[3-9]\d{9}$', "手机号格式错误"), ]
# )
# 验证方式2:钩子方法,设置了field[]后,内部自动生成clean_字段名,拿过来重写
def clean_mobile(self):
txt_mobile = self.cleaned_data["mobile"]
# 验证不通过报错
if len(txt_mobile) != 11:
raise ValidationError("格式错误")
# 验证通过返回用户输入的值
else:
return txt_mobile
class Meta:
model = models.PrettyNum
fields = ["mobile", "price", "level", "status"]
# 直接获取所有字段
# fields = "__all__"
# 排除字段
# exclude = ["level"]
# 向自动生成的输入框添加样式
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for name, field in self.fields.items():
print(name, field)
# 跳过不加样式:
# 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})
else:
form = PrettyModelForm(data=request.POST)
if form.is_valid():
form.save()
return redirect('/pretty_list/')
else:
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">
{# novalidate关闭浏览器校验#}
<form action="/pretty_add/" method="POST" novalidate>
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label>
{{ field.label }}
<span style="color: red">{{ field.errors.0 }}</span>
</label>
{{ field }}
</div>
{% endfor %}
<button type="submit" class="btn btn-default">提交</button>
</form>
</div>
</div>
</div>
{% endblock %}
P41,靓号管理-编辑和删除
重点:
添加校验数据格式是否非法
添加校验数据是否已存在
编辑校验数据是否合法
编辑校验数据是否存在(与添加逻辑不同)def clean
class PrettyEditModelForm(forms.ModelForm):
# mobile = forms.CharField(disabled=True, label="手机号")
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():
print(name, field)
# 跳过不加样式:
# if name == "password":
# continue
field.widget.attrs = {'class': 'form-control', 'placeholder': field.label}
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 len(txt_mobile) != 11:
raise ValidationError("格式错误")
# 验证通过返回用户输入的值
else:
if exists:
raise ValidationError("手机号已存在")
else:
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})
else:
form = PrettyEditModelForm(data=request.POST, instance=row_object)
if form.is_valid():
form.save()
return redirect('/pretty_list/')
else:
return render(request, "pretty_edit.html", {'form': form})
def pretty_del(request, nid):
models.PrettyNum.objects.filter(id=nid).delete()
return redirect('/pretty_list/')
{% 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">
{# novalidate关闭浏览器校验#}
<form method="POST" novalidate>
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label>
{{ field.label }}
<span style="color: #fa7a7a">{{ field.errors.0 }}</span>
</label>
{{ field }}
</div>
{% endfor %}
<button type="submit" class="btn btn-default">提交</button>
</form>
</div>
</div>
</div>
{% endblock %}
P42,靓号管理-搜索
models.PrettyNum.objects.filter(mobile="", id=12)
data_dict = {'mobile':"123213", 'id':123}
models.PrettyNum.objects.filter(**data_dict)
# 数字
models.PrettyNum.objects.filter(id=2)
models.PrettyNum.objects.filter(id__gt=2)
models.PrettyNum.objects.filter(id__gte=2)
models.PrettyNum.objects.filter(id__lt=2)
models.PrettyNum.objects.filter(id__lte=2)
data_dict = {'id__lte":12}
models.PrettyNum.objects.filter(**data_dict)
# 字符串
models.PrettyNum.objects.filter(mobile="")
models.PrettyNum.objects.filter(mobile__startswith="")
models.PrettyNum.objects.filter(mobile__endwith="")
models.PrettyNum.objects.filter(mobile__contains="")
####
#可以集成到pretty_list里面
def pretty_search(request):
data_dict = {}
value = request.GET.get('q')
if value:
data_dict["mobile__contains"] = value
res = models.PrettyNum.objects.filter(**data_dict)
print(res)
return HttpResponse(res.first().mobile)
else:
return HttpResponse("搜素完成")
####
def pretty_list(request):
"""靓号列表"""
# select * from 表 order by level desc;
data_dict = {}
search_data = request.GET.get('q', '')
if search_data:
data_dict['mobile__contains'] = search_data
queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")
# select * from 表 order by level asc;
# models.PrettyNum.objects.all().order_by("level")
for obj in queryset:
print(obj.mobile)
return render(request, 'pretty_list.html', {'queryset': queryset, 'search_data': search_data })
pretty_list
{% 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" aria-hidden="true"></span>
新建靓号
</a>
<div style="float: right; width: 300px;">
{# <input type="text" placeholder="搜索靓号" name="q">#}
<form action="/pretty_list/" method="GET">
<div class="input-group">
<input type="text" class="form-control" placeholder="搜索靓号" name="q" 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><!-- /input-group -->
</form>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<span class="glyphicon glyphicon-th-list" aria-hidden="true"></span>
用户列表
</div>
<div class="panel-body">
<table class="table">
<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>
<th>{{ obj.mobile }}</th>
<th>{{ obj.price }}</th>
<th>{{ obj.get_level_display }}</th>
<th>{{ obj.get_status_display }}</th>
<td>
<a href="/pretty_edit/{{ obj.id }}/" class="btn btn-primary btn-xs">编辑</a>
<a href="/pretty_del/{{ obj.id }}/" class="btn btn-danger btn-xs">删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
{% endblock %}