表结构:
根据表结构的需求,在models.py中创建类。
主要是创建级别和默认级别
class PrettyNum(models):
"""靓号表"""
models = models.CharField(verbose_name="手机号", max_length=32)
price = models.IntegerField(verbose_name="价格")
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
靓号列表
- URL
- 函数:
- 获取所有靓号
- 结合html+render将所有靓号罗列出来
id 号码 价格 级别(中文) 状态(中文)
新建靓号
- 列表点击跳转:/pretty/add/
- url
- ModelForm类
from django import forms
class PrettyModelForm(forms.ModelForm):
- 函数 : 实例化类对象,通过render将对象传入到html中,模板循环展示所有的靓号
-
class PrettyModelForm(forms.ModelForm): class Meta: model = models.PrettyNum # fields = ["mobile", "price", "level", "status"] fields = "__all__" # exclude = ['level'] 排除那个字段 # 保留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} def pretty_add(request): """添加靓号""" form = PrettyModelForm() return render(request, 'pretty_add.html', {"form": form})
使用前面的模板
{% extends 'layout.html' %}
{% load static %}
{% 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-info">提交</button>
</form>
</div>
</div>
</div>
{% endblock %}
提交,数据校验保存到数据库,跳回到靓号列表
号码必须为11位
from django.core.exceptions import ValidationError
# 错误校验
# 号码必须为11位, 钩子方法,clean
def clean_mobile(self):
txt_mobile = self.cleaned_data["mobile"]
if len(txt_mobile) != 11:
raise ValidationError("格式错误")
return txt_mobile
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})