简体   繁体   English

如何在 Django 的两个视图之间传递两个 arguments?

[英]How to pass two arguments between two views in Django?

I am converting a Flask project into Django one.我正在将 Flask 项目转换为 Django 项目。 I have a view1 function that takes user input and passes it to a function1 that returns two variables.我有一个 view1 function 接受用户输入并将其传递给返回两个变量的函数 1。 Variable x is used in query string and passed to view2.变量 x 用于查询字符串并传递给 view2。 However, I also need to pass variable y to view2 for further operations.但是,我还需要将变量 y 传递给 view2 以进行进一步的操作。 I Flask application I used expression 'global y' but this does not work in Django.我在 Flask 应用程序中使用了表达式“全局 y”,但这在 Django 中不起作用。 Any ideas,有任何想法吗,

def function1(input):
  #does something
  return x,y

def view1(request):
  form = SomeForm()
  context={'form': form}
  if request.method == "POST":
    form = SomeForm(request.POST)
    if form.is_valid():
      input = form.cleaned_data['data_from_user']
      # global y --> works only in Flask
      x,y = function1(input)      
      return redirect("view2", x) # goes to path('<str:x>/', views.my_app, name='view2')
  return render(request, "my_app/view1.html", context)

def view2(request, x):
  record = SomeTable.objects.filter(y=y).first()
  context = {'record': record}
  return render(request, "my_app/view2.html", context)

The global would not have worked in Flask either: it might have appeared to in a limited development environment, but would certainly fail in production.全局也不会在 Flask 中工作:它可能在有限的开发环境中出现,但在生产中肯定会失败。 You cannot safely share global data between requests in a multi-process, multi-user environment like a web server.在 web 服务器等多进程、多用户环境中,您无法安全地在请求之间共享全局数据。

If you don't want the data in the URL, you need to save it somewhere persistent.如果您不想要 URL 中的数据,则需要将其保存在某个持久性位置。 In this case the session would be the perfect place.在这种情况下,session 将是完美的选择。

def view1(request):
    ...
    x, y = function(input)
    request.session['y'] = y
    ...

def view2(request, x)
    y = request.session.pop('y', None)

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

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