【问题标题】:how to pass another argument to url django?如何将另一个参数传递给 url django?
【发布时间】:2021-03-22 16:34:51
【问题描述】:

我的 view.py 的 page1.html :

def spwords(request, spray_id)     
  if request.method == 'POST':
    value= request.POST["rangeVal"]  #### the other argument that i want to pass it to views.py of the second page html ...
    form = forms.SpwordsForm(request.POST)

    return HttpResponseRedirect(reverse('sp_url', args=[sp_id]))  # if POST we go to page2.html on this url

在我的 url.py 中:

 url(r'^queries/(.*)$', qviews.sp_queries, name='sp_url')

在我的 Page2.html 的views.py 中:

 def sp_queries(request, sp_id):
      #### here i want to recupere arguments : sp_id and value

我想将第一页html的views.py的value=request.POST[“rangeVal”]传递给第二页html,即我想在“HttpResponseRedirect(reverse('sp_url ', args=[sp_id]))"。

但我想保留 urls.py 的格式:即只是查询/sp_id

【问题讨论】:

    标签: html python-3.x django django-views python-requests-html


    【解决方案1】:

    您可以使用 url 查询字符串。例如:

    url = "{}?rangeVal={}".format(reverse('sp_url', args=[sp_id]),value)
    return HttpResponseRedirect(url)
    

    在这里,我将 rangeVal 的值添加为 url 查询字符串并传递给 HttpResponse。现在要获取sp_queries中的值,可以使用以下代码:

    def sp_queries(request, sp_id):
        value = request.GET.get('rangeVal', None)
    

    替代方案:

    使用request.session。例如:

    if request.method == 'POST':
        value= request.POST["rangeVal"]
        form = forms.SprayKeywordsForm(request.POST)
        request.session['rangeVal'] = value
        return HttpResponseRedirect(reverse('sp_url', args=[sp_id]))
    
    def sp_queries(request, sp_id):
        value = request.session.pop('rangeVal', None)
    

    更多信息,请查看documentation

    【讨论】:

    • 非常感谢,但我不会更改 url 的格式,我只想保留不带 ?rangeVal 的 query/sp_id,因为如果我们这样做,我们必须在 page3 之后更改所有请求.html
    • 我已经更新了我的答案。如果您觉得有帮助,请consider accepting it。谢谢
    猜你喜欢
    • 2015-02-12
    • 1970-01-01
    • 2021-03-30
    • 2018-03-21
    • 2020-09-06
    • 2021-01-16
    • 2011-10-20
    • 1970-01-01
    • 2012-09-25
    相关资源
    最近更新 更多