如何用Django建立一个后台CRM系统04
对增加订单进行优化
-删除home。html模板下的buttom
-在customer。html下增加 {% url ‘create_oreder’ customer.id%}
-优化原来只有单条选择项 增加表单集
-引入form库中的inlineformser_factory表单集
-参考父子模板 Customer Order 字段是foreignkey
from django.forms import inlineformset_factory def CreatOrder(request,pk): OrderFormSet = inlineformset_factory(Customer,Order,fields=('product','status'))
-继承表单集 用instance实例还原原本选项
-对于POST发送方式思路跟原来create_order一样
def CreatOrder(request,pk): OrderFormSet = inlineformset_factory(Customer,Order,fields=('product','status'),extra=6) customer = Customer.objects.get(id=pk) # form = OrderForm(initial={'customer':customer}) formset = OrderFormSet(instance=customer) # formset = OrderFormSet(queryset=Order.objects.none(),instance=customer) if request.method == 'POST': # form = OrderForm(request.POST) formset = OrderFormSet(request.POST,instance=customer) if formset.is_valid(): formset.save() return redirect('/') context = {'form': formset} return render(request,'accounts/orderform.html',context)
-在orderform。html模板下渲染数据
-由于它是表单集 具有多行数据 所以用for循环输出
-直接输出有BUG 需要加入 { { form。management_form }}
{% extends 'accounts/main.html' %} {% load static %} {% block content %} <div class="row"> <div class="col-md"> <div class="card card-body"> <form method="POST" action=""> {% csrf_token %} {{ form.management_form }} {% for item in form %} {{ item }} <br> <br> {% endfor %} <input type="submit" value="Submit"> </form> </div> </div> </div>> {% endblock %}
-搜索框搜索
-添加模块库 pip install Djang-filter
-创建filter。py
import django_filters from .models import * class OrderFilter(django_filters.FilterSet): class Meta: model = Order fields = '__all__'
-在views中的customer中添加函数语句
-myfilter是一个查询集 queryset=order 是选定模板属性
-order = myfilter。qs 目的是为了页面下方显示出查询结果
-不需要显示顾客和时间线 在filter。py中排除
-查询选项增加开始时间和结束时间两条时间线
-在filter。py中添加自定义属性查找 lookup_expr = 'gte' 大于或等于 xxx ‘lte’ 小于或等于
from django_filters import DateFilter,CharFilter class OrderFilter(django_filters.FilterSet): start_date = DateFilter(field_name='date_created',lookup_expr='gte') end_date = DateFilter(field_name='date_created',lookup_expr='lte')
-添加NOTE属性
-models。py的Order增加note属性
-python manage。py makemigrations + python manage。migrate 写入数据库
-在数据库中填入数据
-在customer模板中修改属性 目的是为了显示出来
<table class="table table-sm"> <tr> <th>Product</th> <th>note</th> <th>Date Orderd</th> <th>Status</th> <th>Update</th> <th>Remove</th> </tr> {% for order in order %} <tr> <td>{{ order.product }}</td> <td>{{order.note }}</td> <td>{{ order.date_created }}</td> <td>{{ order.status }}</td> <td><a class="btn btn-sm btn-info" href="{% url 'update_order' order.id %}">Update</a> </td> <td><a class="btn btn-sm btn-danger" href="{% url 'delete_order' order.id %}">Remove</a> </td> </tr> {% endfor %} </table
-在filter。py过滤查询
class OrderFilter(django_filters.FilterSet):
start_date = DateFilter(field_name='date_created',lookup_expr='gte')
end_date = DateFilter(field_name='date_created',lookup_expr='lte')
note = CharFilter(field_name='note', lookup_expr='icontains')
-