I am converting a Flask project into Django one. I have a view1 function that takes user input and passes it to a function1 that returns two variables. Variable x is used in query string and passed to view2. However, I also need to pass variable y to view2 for further operations. I Flask application I used expression 'global y' but this does not work in 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. You cannot safely share global data between requests in a multi-process, multi-user environment like a web server.
If you don't want the data in the URL, you need to save it somewhere persistent. In this case the session would be the perfect place.
def view1(request):
...
x, y = function(input)
request.session['y'] = y
...
def view2(request, x)
y = request.session.pop('y', None)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.