简体   繁体   English

Django - 如何通过重定向传递数据(参数?) function

[英]Django - How to pass data (arguments?) with redirect function

I have a django view where a user uploads a large file.我有一个 django 视图,用户上传一个大文件。 I scrape a ton of information from this file and hold it in memory.我从这个文件中抓取了大量信息并将其保存在 memory 中。 I don't want to save this information to the database because it takes too long and I don't need to save it.我不想将这些信息保存到数据库中,因为它花费的时间太长而且我不需要保存它。 But I want to continue to use this data in the next view.但我想在下一个视图中继续使用这些数据。 How do I send along this data using redirect?如何使用重定向发送这些数据?

def view_one(request):
     if request.method == 'GET':
          return render(request, 'view_one.html')
     if request.method == 'POST':
          uploaded_file = request.FILES['my_file']
          info, data = scrape_my_file_for_info_and_data(uploaded_file)
          return redirect('path_to_view_two', info, data)

def view_two(request, info, data):
     do_stuff_with_info(info)
     do_stuff_with_data(data)

I keep getting errors that I am missing positional arguments 'info' and 'data'.我不断收到错误消息,提示我缺少位置 arguments 'info' 和 'data'。 I've tried doing:我试过做:

return redirect('path_to_view_two', info=info, data=data)
return redirect(view_two(info, data))

But this doesn't work either.但这也不起作用。 I can't find an example online of how to properly do this and I can't make heads or tails out of the django documentation.我在网上找不到如何正确执行此操作的示例,也无法从 django 文档中得出正面或反面。 Seems there should be an easy way to do this, I just haven't landed on it.似乎应该有一个简单的方法来做到这一点,我只是还没有找到它。

Thanks for reading my question!感谢您阅读我的问题!

According to docs you missed quotes in defining positional arguments根据文档,您在定义位置 arguments 时错过了引号

it should be like that:它应该是这样的:

return redirect('path_to_view_two', info='info', data='data')

Also you can consider saving data to user's session and retrieving on the redirected view - sessions docs您也可以考虑将数据保存到用户的 session 并在重定向视图上检索 - 会话文档

def view_one(request):
     data = scrape_my_file_for_info_and_data(uploaded_file)
     request.session['data'] = data

def view_two(request):
     data = request.session.get('data')
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM