写一个Django美妆商城购物车页面
时间: 2024-01-24 14:03:56 浏览: 27
好的,以下是一个简单的Django美妆商城购物车页面的代码示例:
1. 创建一个新的 Django 应用
```
python manage.py startapp cart
```
2. 在 `cart` 应用中创建一个 `views.py` 文件,并添加以下代码:
```python
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
@login_required
def cart(request):
cart_items = request.user.cart_items.all()
context = {
'cart_items': cart_items,
}
return render(request, 'cart.html', context)
```
3. 在 `cart` 应用中创建一个 `cart.html` 模板文件,并添加以下代码:
```html
{% extends 'base.html' %}
{% block content %}
<h1>购物车</h1>
{% if cart_items %}
<table>
<thead>
<tr>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
</tr>
</thead>
<tbody>
{% for item in cart_items %}
<tr>
<td>{{ item.product.name }}</td>
<td>{{ item.product.price }}</td>
<td>{{ item.quantity }}</td>
<td>{{ item.subtotal }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<p>购物车为空。</p>
{% endif %}
{% endblock %}
```
4. 在 `urls.py` 文件中添加一个 `url` 来映射我们的 `cart` 视图:
```python
from django.urls import path
from .views import cart
urlpatterns = [
path('cart/', cart, name='cart'),
]
```
现在,当用户访问 `/cart/` 路由时,将显示购物车页面,该页面将显示当前用户的所有购物车项目。