django传参数到其他页面
时间: 2023-08-19 22:03:55 浏览: 45
要在 Django 中将参数传递到其他页面,可以使用以下方法:
1. 使用 URL 参数:将参数添加到 URL 中,然后在视图函数中获取参数并将其传递给模板。
例如,在 URL 中添加参数:
```python
path('articles/<int:article_id>/', views.article_detail, name='article_detail')
```
然后在视图函数中获取参数并将其传递给模板:
```python
def article_detail(request, article_id):
article = get_object_or_404(Article, pk=article_id)
return render(request, 'article_detail.html', {'article': article})
```
在模板中,可以使用该参数:
```html
<h1>{{ article.title }}</h1>
<p>{{ article.body }}</p>
```
2. 使用会话(Session):将参数存储在会话中,然后在其他视图函数中获取参数。
例如,在视图函数中将参数存储在会话中:
```python
def add_to_cart(request, product_id):
product = get_object_or_404(Product, pk=product_id)
cart = request.session.get('cart', {})
cart[product_id] = {
'id': product_id,
'name': product.name,
'price': str(product.price),
}
request.session['cart'] = cart
return redirect('cart')
```
然后在其他视图函数中获取参数:
```python
def view_cart(request):
cart = request.session.get('cart', {})
total = 0
for item in cart.values():
total += Decimal(item['price'])
return render(request, 'cart.html', {'cart': cart, 'total': total})
```
在模板中,可以使用该参数:
```html
{% for item in cart.values %}
<h2>{{ item.name }}</h2>
<p>{{ item.price }}</p>
{% endfor %}
```