0

In my Django app's views.py I'm passing in a GET request to a function definition. How do I check for an optional parameter in that request (like &optional='All') and if that optional parameter is missing, add it. This is all before the request is sent to the template to be rendered.

This is what I have so far:

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')
NewToJS
  • 2,011
  • 4
  • 35
  • 62
  • 2
    Possible duplicate of [Capturing url parameters in request.GET](https://stackoverflow.com/questions/150505/capturing-url-parameters-in-request-get) – voodoo-burger Jun 08 '18 at 22:02

1 Answers1

0

In your view, you have access to request.GET, With it you can set new value to a specific URL from that view. As you mentioned, add the optional value to GET parameter is possible. So we can proceed by redirecting the user to the correct view in case the value optional is missing or not equal to 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')
Lemayzeur
  • 8,297
  • 3
  • 23
  • 50