Django开发物流web应用(二)-订单系统构建
参考: Django2.2 中文文档
1. setting.py配置
-
DEBUG = True
: 是否为调试模式 -
INSTALLED_APPS
: 已安装的Django应用 -
DATABASES
: 使用的数据库
修改时区和语言
LANGUAGE_CODE = 'zh-hans'
TIME_ZONE = 'Asia/Shanghai'
2. 执行数据迁移
新创建的app需要创建一些数据表
运行:
python manage.py migrate
编辑 orders/models.py
class Order(models.Model):
def __str__(self):
return self.name
name = models.CharField(max_length=200)
sender = models.CharField(max_length=200)
recipient = models.CharField(max_length=200)
position = models.CharField(max_length=200)
status = models.CharField(max_length=200)
将app添加至settings
INSTALLED_APPS = [
...
'orders.apps.OrdersConfig',
]
- 最后执行数据库迁移
3. Django管理员
运行 python manage.py createsuperuser
并在 orders/admin.py里注册模型
...
from . models import Order
...
admin.site.register(Order)
4. 前端展示, 并添加订单
前端html页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{% for order in orders %}
<div>{{ order.name }}<div>
{% empty %}
<div>no orders<div>
{% endfor %}
<form action="/orders/" method="post">{% csrf_token %}
<input type="text" name="order_name">
<input type="text" name="order_sender">
<input type="text" name="order_recipient">
<input type="text" name="order_position">
<input type="text" name="order_status">
<input type="submit" value="提交">
</form>
</body>
</html>
views.py
from django.shortcuts import render
from django.http import HttpResponse
from .models import Order
def create_order(request):
new_order = Order()
name = request.POST.get('order_name', '')
sender = request.POST.get('order_sender', '')
recipient = request.POST.get('order_recipient', '')
position = request.POST.get('order_position', '')
status = request.POST.get('order_status', '')
new_order.name = name
new_order.sender = sender
new_order.recipient = recipient
new_order.position = position
new_order.status = status
new_order.save()
def order_list(request):
request.encoding='utf-8'
if request.POST.get('order_name'):
create_order(request)
all_orders = Order.objects.all()
context = {}
context['orders'] = all_orders
return render(request, 'orders/order_list.html', context)
def index(request):
return HttpResponse("Hello")
- create_order: 向数据库添加新订单
网友评论