代码之家  ›  专栏  ›  技术社区  ›  NewToJS

Django:向视图中的请求添加可选参数

  •  0
  • NewToJS  · 技术社区  · 6 年前

    在我的Django应用程序中 views.py 我正在将GET请求传递给函数定义。如何检查该请求中的可选参数(例如 &optional='All' )如果该可选参数丢失,则添加它。这是在请求发送到要呈现的模板之前的全部内容。

    这就是我目前所拥有的:

    def my_function(request):
    
        #get all the optional parameters 
        optional_params_list = request.GET.keys()
    
        #see if filter_myfilter is NOT an optional param
        if 'filter_myfilter' not in optional_params_list:
          #add filter_myfilter as a parameter and set it equal to All
          request.filter_myfilter = 'All'
    
        return render(request, 'quasar.html')
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Lemayzeur    6 年前

    在您看来,您可以访问 request.GET ,使用它,您可以从该视图为特定的URL设置新值。如您所述,添加 optional 获取参数的值是可能的。因此,我们可以将用户重定向到正确的视图,以防 可选择的 缺失或不等于 All .

    
    from django.http import HttpResponseRedirect
    from django.core.urlresolvers import reverse
    
    def my_function(request):
    
        param = request.GET.get('param','All')
        if param != 'All':
            return HttpResponseRedirect(reverse('url_name') + "?optional=All")
            # or
            # return HttpResponseRedirect(request.path + "?optional=All")
        return render(request, 'quasar.html')