models.py模型文件
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
class Adm(models.Model): #用于存储管理员名称
name = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.name.username
class Customer(models.Model): #客户信息
name = models.CharField(max_length=50,null=False)
belong_to = models.ForeignKey(User,on_delete=models.DO_NOTHING) #所属业务员
remark = models.CharField(max_length=200,null=True,default=' ') #备注
def __str__(self):
return self.name
class Order(models.Model): # 订单信息,因为不要做统计,顾设置的比较简单
e_name = models.CharField(max_length=20)
c_name = models.ForeignKey(Customer, on_delete=models.DO_NOTHING) # 客户名称
new_choice = (('yes','新客户'),('no','老客户'))
is_new = models.CharField(max_length=6,choices=new_choice,default='no') # 是否新客户
p_make = models.CharField(max_length=30,default=' ') # 品牌
p_name = models.CharField(max_length=50,default=' ') # 产品
p_spec = models.CharField(max_length=20,default=' ') #规格
p_price = models.CharField(max_length=15,default=' ') #单价
p_num = models.CharField(max_length=20, default=' ') #数量
invoice_choice = (('after','后开票'),('pre','预付款'))
invoice_stat = models.CharField(max_length=10,choices=invoice_choice,default='after') # 记录发票
p_time = models.DateTimeField(default=timezone.now) # 记录订单生成时间
h_name = models.CharField(max_length=15,default='') # 记录处理者名称
h_time = models.DateTimeField(auto_now=True) # 记录订单处理时间
stats_choice = (('done','已处理'),('waiting','未处理'))
order_stat = models.CharField(max_length=10,choices=stats_choice,default='waiting') #记录订单是否处理
remark = models.CharField(max_length=200,default='') #备注
huohao = models.CharField(max_length=100,default='') #货号
def __str__(self):
return self.c_name.name + ' ' + self.p_make + ' ' + self.p_name + ' ' + self.p_spec
views.py视图函数文件,里面部分小功能跟实际使用的比做了一些重构,使代码更简洁
from django.shortcuts import render, HttpResponseRedirect, Http404
from django.urls import reverse
from .forms import OrderForm, CustomerForm
from .models import Customer, Order, Adm
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from datetime import timedelta, datetime
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def index(request):
return render(request, 'index.html')
def paginator_test(request, orders): # 分页函数,参数是发起的请求和获得的订单查询结果对象
paginator = Paginator(orders, 10) # 每页10条结果
page = request.GET.get('page') # 获取查询的请求页面
try:
orders = paginator.page(page) # 获取查询页
except PageNotAnInteger:
orders = paginator.page(1) # 如果不是整数,返回第1页
except EmptyPage:
orders = paginator.page(paginator.num_pages) # 如果超出范围,返回最后1页
return orders, page
def test_adm(request): # 检查访问者是否是管理员
try:
Adm.objects.get(name=request.user)
return True
except:
return False
@login_required
def orders(request):
"""业务员查询到个人所有订单,管理员查询到所有业务员订单,可以设置简单条件筛选"""
adm = test_adm(request)
if adm:
orders = Order.objects.order_by('-p_time')
else:
orders = Order.objects.filter(e_name=request.user.username).order_by('-p_time')
if request.method == "POST":
or_stat = request.POST.get('or_stat')
in_stat = request.POST.get('in_stat')
if or_stat != 'all':
orders = orders.filter(order_stat=or_stat)
if in_stat != 'all':
orders = orders.filter(invoice_stat=in_stat)
orders, page = paginator_test(request, orders)
context = {'orders': orders, 'adm': adm, 'page': page}
return render(request, 'orders.html', context)
@login_required
def customers(request):
"""业务员显示自己所有客户,管理员显示所有业务员客户"""
adm = test_adm(request)
if adm:
customers = Customer.objects.order_by('name')
else:
customers = Customer.objects.filter(belong_to=request.user).order_by('name')
context = {'customers': customers, 'adm': adm}
return render(request, 'customers.html', context)
@login_required
def someone_customers(request, user_id):
"""查询某个业务员所有客户"""
try:
user = User.objects.get(id=user_id) # 如果有手动输入,判断用户是否存在
except:
raise Http404
adm = test_adm(request)
if not adm: # 如果不是管理员,不许访问此函数
return HttpResponseRedirect(reverse('order:customers'))
customers = user.customer_set.all() # 获得用户所有客户
context = {'customers': customers, 'adm': adm}
return render(request, 'customers.html', context)
def check_legal(request, customer):
if not test_adm(request): # 如果不是管理员,对他人订单任何操作都抛出错误
if customer.belong_to.username != request.user.username: # 如果客户所属业务员和访问者不是同一人
raise Http404
return True
@login_required
def customer(request, customer_id):
"""显示单个用户的所有订单,业务员查询单个客户订单时,不显示业务员名和老师名"""
try: # 客户不存在则报错,手动输入存在错误
customer = Customer.objects.get(id=customer_id)
except:
raise Http404
check_legal(request, customer)
orders = customer.order_set.order_by('-p_time') # 获得要查询用户的所有订单
orders, page = paginator_test(request, orders) # 使用分页函数,获取分页情况
context = {'orders': orders, 'customer': customer, 'page': page}
return render(request, 'customer.html', context)
@login_required
def new_customer(request):
if request.method != "POST":
form = CustomerForm(initial={'remark': '选填'}) # 初始化备注内容
else:
form = CustomerForm(data=request.POST) # 获得提交数据
if form.is_valid(): # 验证数据的有效性
new_customer = form.save(commit=False) # 保存数据,但是暂时不提交
new_customer.belong_to = request.user # 关联客户与业务员
new_customer.save() # 保存数据
return HttpResponseRedirect(reverse('order:customers'))
context = {'form': form} # 把表单传递给网页
return render(request, 'new_customer.html', context)
@login_required
def new_order(request, customer_id):
try: # 判断是否正常,排除手动输入出错情况
customer = Customer.objects.get(id=customer_id)
except:
raise Http404
check_legal(request, customer)
if request.method != "POST": # 以GET方式打开页面,进行一些非必填项初始化
form = OrderForm(initial={'e_name': request.user,'c_name': customer, 'p_make': '选填', 'p_spec': '选填', 'remark': '选填'})
else:
form = OrderForm(data=request.POST)
if form.is_valid():
new_order = form.save(commit=False)
new_order.c_name = customer
new_order.save()
return HttpResponseRedirect(reverse('order:customer', args=[customer_id])) # 返回该客户所有订单
context = {'customer': customer, 'form': form}
return render(request, 'new_order.html', context)
@login_required
def edit_order(request, order_id):
"""编辑订单"""
try:
order = Order.objects.get(id=order_id)
except:
raise Http404
customer = order.c_name
check_legal(request, customer)
if request.method != "POST":
form = OrderForm(instance=order) # 初始化要修改的数据表单
else:
form = OrderForm(instance=order, data=request.POST) # 获取表单提交数据
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('order:customer', args=[customer.id]))
context = {'order': order, 'customer': customer, 'form': form}
return render(request, 'edit_order.html', context)
@login_required
def edit_customer(request, customer_id):
"""编辑客户"""
try:
customer = Customer.objects.get(id=customer_id)
except:
raise Http404
check_legal(request, customer)
if request.method != "POST":
form = CustomerForm(instance=customer)
else:
form = CustomerForm(instance=customer, data=request.POST)
form.save()
return HttpResponseRedirect(reverse('order:customers'))
context = {'customer': customer, 'form': form}
return render(request, 'edit_customer.html', context)
@login_required
def del_order(request, order_id):
"""删除订单"""
try:
order = Order.objects.get(id=order_id)
except:
raise Http404
customer = order.c_name
check_legal(request, customer)
order.delete()
return HttpResponseRedirect(reverse('order:orders'))
@login_required
def done(request, order_id):
"""管理员确认订单处理,修改订单状态"""
try: # 验证订单真实性
get_order = Order.objects.get(id=order_id)
except:
raise Http404
customer = get_order.c_name
check_legal(request, customer)
get_order.order_stat = 'done' # 修改订单状态
get_order.h_name = request.user.username # 修改订单处理人
get_order.save()
return HttpResponseRedirect(reverse('order:orders'))
@login_required
def search(requset):
"""订单搜索"""
global tem_search # 定义变量,存储中间搜索结果
try:
cur_user = Adm.objects.get(name=requset.user)
# 如果当前用户是管理员,则返回所有客户
customers = Customer.objects.all()
except:
# 否则之返回登录用户的所有客户
customers = User.objects.get(username=requset.user.username).customer_set.all()
context = {'customers': customers}
if requset.GET.get('page'):
orders = tem_search
orders, page = paginator_test(requset, orders)
context.update({'orders': orders, 'page': page})
elif requset.method == 'POST':
"""获取搜索条件"""
cust_id = requset.POST.get('customer')
or_stat = requset.POST.get('or_stat')
in_stat = requset.POST.get('in_stat')
date_s = requset.POST.get('date_s')
date_e = requset.POST.get('date_e')
date_e = datetime.strptime(date_e, "%Y-%m-%d") + timedelta(days=1) # 增加一天的时间偏移量,获取的时间默认为日期的0点
cus_obj = Customer.objects.get(id=cust_id) # 获取要查询的客户
orders = cus_obj.order_set.order_by('-p_time') # 获得该客户的所有订单
if or_stat != 'all':
orders = orders.filter(order_stat=or_stat)
if in_stat != 'all':
orders = orders.filter(invoice_stat=in_stat)
orders = orders.filter(p_time__range=(date_s, date_e))
tem_search = orders # 把搜索结果存储起来
orders, page = paginator_test(requset, orders)
context.update({'orders': orders, 'page': page})
return render(requset, 'search.html', context)
forms.py django自带表单管理模块
from django import forms
from .models import Order,Customer
class OrderForm(forms.ModelForm):
class Meta:
model = Order
fields = ['e_name', 'c_name', 'is_new', 'p_make', 'p_name', 'huohao','p_spec', 'p_price', 'p_num', 'invoice_stat', 'remark']
labels = {'e_name':'业务员', 'c_name': '客户名', 'is_new': '是否新用户', 'p_make': '品牌', 'huohao':'货号','p_name': '产品名称', 'p_spec': '规格', 'p_price': '价格',
'p_num': '数量', 'invoice_stat': '发票', 'remark': '备注'}
widgets = {'remark': forms.Textarea(attrs={'cols': 50}),'e_name':forms.HiddenInput()}
class CustomerForm(forms.ModelForm):
# remark = forms.CharField(required=False) #设置该字段非必填
class Meta:
model = Customer
fields = ['name','remark']
labels = {'name':'客户名','remark':'备注'}
widgets = {'remark':forms.Textarea(attrs={'cols':50})}
urls.py路由配置文件
from django.urls import re_path # 默认正则需要使用re_path
from . import views
urlpatterns = [
re_path('^$',views.index,name='index'), #首页
re_path('^orders/$',views.orders,name='orders'), #查看所有订单
re_path('^new_order/(?P<customer_id>\d+)/$',views.new_order,name='new_order'), #创建新订单
re_path('^customers/$',views.customers,name='customers'), #显示用户所有客户
re_path('^customer/(?P<customer_id>\d+)/$',views.customer,name='customer'), #显示该客户所有订单
re_path('^new_customer/$', views.new_customer, name='new_customer'), #创建新客户
re_path('^edit_order/(?P<order_id>\d+)/$',views.edit_order,name='edit_order'), #编辑订单
re_path('^edit_customer/(?P<customer_id>\d+)/$',views.edit_customer,name='edit_customer'),
re_path('^del_order/(?P<order_id>\d+)/$',views.del_order,name='del_order'),
re_path('^done/(?P<order_id>\d+)/$',views.done,name='done'),
re_path('^someone_customers/(?P<user_id>\d+)/$',views.someone_customers,name='someone_customers'),
re_path('^search/$',views.search,name='search'),
]
admin.py后台管理注册数据模型,如果想在后台看到更多显式格式,网上有很多资料
from django.contrib import admin
from .models import Customer,Order,Adm
admin.site.register(Customer)
admin.site.register(Order)
admin.site.register(Adm)