简体   繁体   English

django 带参数的重定向视图

[英]django redirect view with parameter

In my App I have the file urls.py that contains these rows:在我的应用程序中,我有包含以下行的文件 urls.py:

...
path('home/', views.home, name='home'),
path('page/', views.page, name='page'),
....

and in my view.py file i have two view like this:在我的 view.py 文件中,我有两个这样的视图:

def home(request, value=0):
    print("value=", value)
    return render(request, 'template.html', context)


def page(request):
    if bad:
        return redirect(reverse('home'), value=1)

Is it possible to have the view function with a parameter (like the value in this case) and then use redirection from the page view passing some value based on the same condition like value=1, in this case, using the format described in the urls.py?是否可以让视图 function 带有参数(如本例中的值),然后使用来自页面视图的重定向,基于相同的条件(如 value=1)传递一些值,在这种情况下,使用中描述的格式网址.py? The code above always prints value=0 no matter what.无论如何,上面的代码总是打印 value=0 。

The only way I can think to do this is to use global variables which I would really like to avoid...我能想到的唯一方法是使用我真的想避免的全局变量......

Yes, but you need to add the parameter to the URL:可以,但是需要在URL中添加参数:

path('home/', views.home, name='home1'),
path('home/<int:value>/', views.home, name='home2'),

Then you need to pass the page in the redirect itself, together with the name of the view, you should not use reverse(..) here:然后你需要在重定向本身中传递页面,连同视图的名称,你不应该在这里使用reverse(..)

def page(request):
    if bad:
        return redirect('home2', value=1)

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

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