一. 在views.py文件的PrettyModelForm类中添加钩子方法
class PrettyModelForm(forms.ModelForm):
# 对提交的字段验证方式1:
mobile = forms.CharField(
# 字段
label="手机号",
# 正则表达式(1开头,再只能3-9里面选择,后面只能9个数,报错)
validators=[RegexValidator(r'^1[3-9]\d{9}$', '手机号格式错误')]
)
class Meta:
model = models.PrettyNum
fields = ["mobile", "price", "level", "status"] # 获取字段
# fields = "--__all__" # 全部字段
# exclude = ['level'] # 排除 level字段
def __init__(self, *args, **kwargs): # 重新定义类的初始属性
super().__init__(*args, **kwargs) # 只要重新执行就继承复类的初始属性
# 循环找到所有的插件,添加了class="form-control"
for name, field in self.fields.items(): # 循环找到所有字段的插件
# if name == "password": # 不想让x字段不加样式
# continue # 绕过去
# 字段.插件 = (每个插件添加上样式)
field.widget.attrs = {"class": "form-control", "placeholder": field.label}
# 对提交的字段验证方式2:
# def clean_mobile(self):
# txt_mobile = self.cleaned_data["mobile"] # 获取用户传入的数据
# if len(txt_mobile) != 11: # 如果传入的数据长度不等于11
# # 验证不通过
# raise ValidationError('格式错误')
# # 验证通过
# return txt_mobile # 返回
# 钩子方法:对提交手机号不能重复
def clean_mobile(self):
txt_mobile = self.cleaned_data["mobile"] # 获取用户传入的数据
print(txt_mobile)
exists = models.PrettyNum.objects.filter(mobile=txt_mobile).exists() # exists()=数据是否存在
print(exists)
if exists:
raise ValidationError('手机号以存在')
# 验证通过
return txt_mobile # 返回
二. 添加搜索功能
1. 更新 pretty_list 函数
def pretty_list(request):
""" 靓号列表 """
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") # 没有输入就获取所有的
return render(request, 'pretty_list.html',{"queryset":queryset,"search_data": search_data})
2.更新pretty_list.html文件 添加搜索框和get表单提交
{% extends 'layout.html' %} <!-- 继承模板 -->
{% block content %} <!-- django导入语法 -->
<div class="container">
<div style="margin-bottom: 10px" class="clearfix">
<a class="btn btn-success" href="/pretty/add/">
<span class="glyphicon glyphicon-plus-sign" aria-hidden="true"></span>
新建靓号
</a>
<div style="float: right;width: 300px;"> <!-- 搜索框宽300,右飘 -->
<form method="get"> <!-- 表单提交 -->
<div class="input-group"> <!-- name属性="q" -->
<input type="text" name="q" class="form-control" placeholder="Search for..."
value="{{ search_data }}"> <!-- 把后端获取的值再传入前端以get方式提交 -->
<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">
<!-- 面板内容 -->
<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 %} <!-- 模板结束 -->