提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
一、前端修改数据库
- 创建一个修改的html前端
- 在首页里添加跳转到修改界面的按钮
- urls.py里面添加相应的链接
- 在views.py中添加与修改相对应的方法
二、实现步骤
1. 创建一个修改的html前端
{% extends 'aoapp/index.html' %}
{% block title %}修改订单{% endblock %}
{% block content %}
<div class="container-fluid">
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<div style="height: 100px"></div>
<div class="card shadow">
<div class="card-header text-center text-light bg-dark">
<h3 class="card-title">Order Form</h3>
</div>
<div class="card-body">
<form action="{% url 'updateorder' order.id %}" method="post">
{% csrf_token %}
{{ o_form.as_p }}
<div class="text-center">
<button type="submit" class="btn btn-primary">提交</button>
</div>
</form>
</div>
</div>
</div>
<div class="col-md-4"></div>
</div>
</div>
{% endblock %}
2. 在首页里添加跳转到修改界面的按钮
{% for i in order reversed %}
<tr>
<th scope="row">{{ i.id }}</th>
<td>{{ i.customer }}</td>
<td>{{ i.product }}</td>
<td>{{ i.time_created }}</td>
<td>{{ i.status }}</td>
<td>
<a href="{% url 'updateorder' i.id %}" class="btn btn-primary">update</a>
</td>
</tr>
{% endfor %}
3. urls.py里面添加相应的链接
因为在首页需要传递id进行查找并修改,str:pk这样,搭配{% url ‘updateorder’ i.id %}
path('updateorder/<str:pk>/', update_order,name='updateorder'),
4. 在views.py中添加与修改相对应的方法
def update_order(request, pk):
order = Order.objects.get(id=pk)
o_form = OrderForm(instance=order)
if request.method == 'POST':
o_form = OrderForm(request.POST)
if o_form.is_valid():
customer_get = o_form.cleaned_data['customer']
product_get = o_form.cleaned_data['product']
status_get = o_form.cleaned_data['status']
# get的东西无法使用update
order = Order.objects.filter(id=pk)
# try:
order.update(id=pk, customer=customer_get, product=product_get, status=status_get)
# except :
# print('666')
return redirect('homepage')
context = {
'order': order,
'o_form': o_form,
}
return render(request, "aoapp/updateorder.html", context)