路由优化
实现一个简单的路由分发
#settings.py
path('price3/', db.Price3.urls()),
#views.db.py
from django.urls import path
from django.shortcuts import HttpResponse
class BaseCurd(object):
@classmethod
def urls(cls):
instance = cls()
return [
path('list/', instance.list, name='level3_list'),
path('add/', instance.add, name='level3_add'),
], None, None
def list(self, request):
return HttpResponse("list")
def add(self, request):
return HttpResponse("add")
class Price3(BaseCurd):
pass
#settings.py
"level3_list": {"parent": None, "text": "级别管理2"},
"level3_add": {"parent": "level3_list", "text": "新建级别"},
Customer功能
from django.shortcuts import render, redirect
from app01 import models
from django import forms
from django.core.exceptions import ValidationError
from utils.boostrap import BootStrapForm
from utils.pager import Pagination
from utils.encrypt import md5
class CustomerModelForm(BootStrapForm, forms.ModelForm):
exclude_field_list = ['level']
confirm_password = forms.CharField(
label="重复密码",
widget=forms.PasswordInput(render_value=True)
)
class Meta:
model = models.Customer
fields = ['level', "username", 'mobile', 'password', 'confirm_password', ]
widgets = {
'password': forms.PasswordInput(render_value=True),
"level": forms.RadioSelect(attrs={'class': "form-radio"})
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# self.fields['level'].queryset = models.Level.objects.filter(active=1)
def clean_password(self):
password = self.cleaned_data['password']
return md5(password)
def clean_confirm_password(self):
password = self.cleaned_data.get('password')
confirm_password = md5(self.cleaned_data.get('confirm_password', ''))
if password != confirm_password:
raise ValidationError("密码不一致")
return confirm_password
def customer_list(request):
queryset = models.Customer.objects.filter(active=1).order_by("-id")
pager = Pagination(request, queryset)
return render(request, "customer_list.html", {"pager": pager})
def customer_add(request):
origin = request.GET.get("redirect", "/home/")
if request.method == "GET":
form = CustomerModelForm()
return render(request, "form.html", {"form": form})
form = CustomerModelForm(data=request.POST)
if not form.is_valid():
return render(request, "form.html", {"form": form})
form.instance.creator_id = request.nb_user.id
form.save()
from django.contrib import messages
messages.add_message(request, messages.SUCCESS, "新建客户成功")
return redirect(origin)
搜索
from django.db.models import Q
def customer_list(request):
keyword = request.GET.get("keyword", "").strip()
# 传统的筛选
# models.Customer.objects.filter(active=1).filter(username__contains=keyword,mobile__contains=keyword).order_by("-id")
# Q查询
con = Q()
if keyword:
con.connector = "OR"
con.children.append(("username__contains", keyword))
con.children.append(("mobile__contains", keyword))
con.children.append(("level__title__contains", keyword))
queryset = models.Customer.objects.filter(active=1).filter(con).order_by("-id")
pager = Pagination(request, queryset)
return render(request, "customer_list.html", {"pager": pager, "keyword": keyword})
{% extends 'layout.html' %}
{% load common %}
{% load permission %}
{% block content %}
<div id="pageMsg" >
{% for message in messages %}
<div class="alert alert-{{ message.tags }}" role="alert">{{ message }}</div>
{% endfor %}
</div>
<div >
<!-- 权限判断 -->
{% if request|has_permission:"customer_add" %}
<a class="btn btn-primary" href">添加</a>
{% endif %}
<div class="right">
<form class="form-inline" method="GET">
<div class="form-group">
<input name="keyword" type="text" class="form-control" placeholder="请输入关键字" value="{{ keyword }}">
</div>
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</form>
</div>
</div>
<table class="table table-bordered">
<thead>
<tr>
<th>序号</th>
<th>用户名</th>
<th>级别</th>
<th>手机号</th>
<th>账户余额</th>
<th>创建日期</th>
<th>重置密码</th>
<th>选项</th>
</tr>
</thead>
<tbody>
{% for row in pager.queryset %}
<tr>
<td>{% loop_counter request forloop.counter %}</td>
<td>{{ row.username }}</td>
<td>{{ row.level.title }}({{ row.level.percent }}%折扣)</td>
<td>{{ row.mobile }}</td>
<td>{{ row.balance }}</td>
<td>{{ row.create_date|date:"Y-m-d H:i:s" }}</td>
<td>
<a href>重置密码</a>
</td>
<td>
{% if request|has_permission:"customer_edit" %}
<a class="btn btn-success btn-xs" href>编辑</a>
{% endif %}
{% if request|has_permission:"customer_delete" %}
<a class="btn btn-danger btn-xs"
href>删除</a>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{{ pager.html }}
{% endblock %}
{% block js %}
<script>
setTimeout(function (){
$("#pageMsg").empty();
},5000);
</script>
{% endblock %}
组件封装
level3 && price3:
from django.shortcuts import render, redirect
from django import forms
from utils.boostrap import BootStrapForm
from app01 import models
from utils.pager import Pagination
from django.urls import path
class BaseCurd(object):
list_template_name = "db_list.html"
def __init__(self, view_list, prefix):
self.view_list = view_list
self.prefix = prefix
def dispatch(self, func):
def inner(request, *args, **kwargs):
# self.request = request
res = func(request, *args, **kwargs)
return res
return inner
@classmethod
def urls(cls, view_list=None, prefix=None):
if not view_list:
view_list = ["list", "add", "edit", "delete"]
if not prefix:
prefix = cls.__name__.lower()
# 实例化对象
instance = cls(view_list, prefix)
router = []
for item in view_list:
func = getattr(instance, item)
if item in ["list", "add"]:
router.append(path(f'{item}/', instance.dispatch(func), name=f"{prefix}_{item}"))
else:
router.append(path(f'{item}/<int:pk>/', instance.dispatch(func), name=f"{prefix}_{item}"))
extra_router = instance.get_extra_url()
if extra_router:
router.extend(extra_router)
return router, None, None
def get_extra_url(self):
pass
def get_queryset(self, request):
return self.queryset
def list(self, request):
queryset = self.get_queryset(request)
pager = Pagination(request, queryset)
context = {
"pager": pager,
"url_add_name": f"{self.prefix}_add",
"url_edit_name": f"{self.prefix}_edit",
"url_delete_name": f"{self.prefix}_delete",
"table_header": self.table_header,
"table_field": self.table_field
}
return render(request, self.list_template_name, context)
def add(self, request):
form_class = self.form_class
origin = request.GET.get("redirect")
if request.method == "GET":
form = form_class()
return render(request, "form2.html", {"form": form})
form = form_class(data=request.POST)
if not form.is_valid():
return render(request, "form2.html", {"form": form})
form.save()
return redirect(origin)
def get_instance(self, request, nid):
return self.instance
def edit(self, request, pk):
origin = request.GET.get("redirect")
# instance = models.Level.objects.filter(id=nid, active=1).first()
instance = self.get_instance(request, pk)
form_class = self.form_class
if request.method == "GET":
form = form_class(instance=instance)
return render(request, "form2.html", {"form": form})
form = form_class(data=request.POST, instance=instance)
if not form.is_valid():
return render(request, "form2.html", {"form": form})
form.save()
return redirect(origin)
def delete(self, request, pk):
origin = request.GET.get("redirect")
if request.method == "GET":
return render(request, 'delete.html', {"origin": origin})
# models.PricePolicy.objects.filter(id=nid).delete()
self.do_delete(request, pk)
return redirect(origin)
def do_delete(self, request, pk):
pass
# ################ 价格管理 ################
class PriceModelForm(BootStrapForm, forms.ModelForm):
class Meta:
model = models.PricePolicy
fields = ["count", "price"]
class Price3(BaseCurd):
queryset = models.PricePolicy.objects.all().order_by("count")
table_header = ["数量", "价格"]
table_field = ["count", "price"]
form_class = PriceModelForm
def get_instance(self, request, nid):
return models.PricePolicy.objects.filter(id=nid).first()
def do_delete(self, request, nid):
models.PricePolicy.objects.filter(id=nid).delete()
# ################ 级别管理 ################
class LevelModelForm(BootStrapForm, forms.ModelForm):
class Meta:
model = models.Level
fields = ["title", "percent"]
class Level3(BaseCurd):
queryset = models.Level.objects.filter(active=1).order_by("-percent")
table_header = ["标题", "百分比"]
table_field = ["title", "percent"]
# table_field = [("db", "title"), ("db", "percent"), ("func", more)]
form_class = LevelModelForm
def get_instance(self, request, nid):
return models.Level.objects.filter(id=nid).first()
def do_delete(self, request, nid):
models.Level.objects.filter(id=nid, active=1).update(active=0)