如何用Django建立一个后台CRM系统03
对订单内容增加的url方式
-在urls.py中增添url
path('creat_order/',views.CreatOrder,name='creat_order'),
-设置HTML页面设置跳转
<a class="btn btn-primary btn-sm btn-block" href="{% url 'creat_order' %}">Create Order</a>
-在views中编写函数
-a 需要在数据库取得数据 才能进行填充
创建一个forms。py 利用frrom django。form import ModalForm 继承model.py中的Order模型
其中fields 相当于 {‘products’,‘customer’,‘status’} 抓取全部成员
from django.forms import ModelForm from .models import Order class OrderForm(ModelForm): class Meta: model = Order fields = '__all__'
-b 在viess中编写函数
OrderForm已经成功抓取数据
from .forms import OrderForm def CreatOrder(request): form = OrderForm() if request.method == 'POST': form = OrderForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request,'accounts/orderform.html',context)
-在templates模板中编写orderform.html
-继承main模板
-{% csrf_token %} 是会form表单数据的加密保护
{% extends 'accounts/main.html' %} {% load static %} {% block content %} <form method="POST" action=""> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock %}
对订单内容修改数据的url方法
-与增加操作步骤一样 url view templates
-<str:pk>主键用get传递参数
path('update_order/<str:pk>/',views.UpdateOrder,name='update_order'),
-跳转 order。id是参数
<td><a class="btn btn-sm btn-info" href="{% url 'update_order' order.id %}">Update</a> </td>
-views函数
-加上变量pk 用于获取目标订单
-与增加操作不同 修改操作需要将原来的数据填充上 所以使用instence
def UpdateOrder(request,pk): order = Order.objects.get(id=pk) form = OrderForm(instance=order) if request.method=='POST': form = OrderForm(request.POST,instance=order) if form.is_valid(): form.save() return redirect('/') context ={'form':form} return render(request, 'accounts/orderform.html', context)
-模板
{% extends 'accounts/main.html' %} {% load static %} {% block content %} <form method="POST" action=""> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock %}
-对订单内容的删除操作步骤与修改操作类似
path('dalete_order/<str:pk>/',views.DeleteOrder,name='delete_order'),
<td><a class="btn btn-sm btn-danger" href="{% url 'delete_order' order.id %}">Remove</a> </td>
def DeleteOrder(request, pk): order = Order.objects.get(id=pk) if request.method== 'POST': order.delete() return redirect('/') context = {'item':order} return render(request,'accounts/delete.html',context)
{% extends 'accounts/main.html' %} {% load static %} {% block content %} <br> <div class="row"> <div class="col-md"> <div class="card card-header"> <p>ARE you sure delete thid {{ item }}?</p> </div> <div class="card card-body"> <p> <form method="POST" action="{% url 'delete_order' item.id %}"> {% csrf_token %} <input class="btn btn-danger" type="submit" value="Comfire"> <a class="btn btn-sm btn-warning" href="{% url 'home' %}">Cancel</a> </form> </div> </div> </div> {% endbloc