python中redirect如何传值_浅谈在django中使用redirect重定向数据传输的问题
时间: 2023-11-27 15:54:20 浏览: 56
在 Django 中使用 `redirect` 进行重定向时,可以通过 URL 参数或者 session 来传递数据。
1. 通过 URL 参数传递数据
在原视图函数中将数据转换成 URL 参数,在重定向时将参数带上即可。示例代码如下:
```python
from django.urls import reverse
from django.shortcuts import redirect
def original_view(request):
data = {'name': 'Alice', 'age': 18}
url = reverse('redirected_view') + '?name={}&age={}'.format(data['name'], data['age'])
return redirect(url)
def redirected_view(request):
name = request.GET.get('name')
age = request.GET.get('age')
# do something with name and age
return HttpResponse('Hello, {}! You are {} years old.'.format(name, age))
```
2. 通过 session 传递数据
在原视图函数中将数据存入 session 中,在重定向后的视图函数中从 session 中取出数据即可。示例代码如下:
```python
from django.urls import reverse
from django.shortcuts import redirect
def original_view(request):
data = {'name': 'Alice', 'age': 18}
request.session['data'] = data
return redirect(reverse('redirected_view'))
def redirected_view(request):
data = request.session.get('data')
name = data.get('name')
age = data.get('age')
# do something with name and age
return HttpResponse('Hello, {}! You are {} years old.'.format(name, age))
```
需要注意的是,如果使用 session 传递数据,需要在 `settings.py` 中设置 session 的存储方式。例如:
```python
SESSION_ENGINE = 'django.contrib.sessions.backends.db'
```
以上是在 Django 中使用 `redirect` 进行重定向时传递数据的两种方式。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)