1

here i got one endpoint to receive multiple query parameters namely first_name, last_name. location and i need the endpoint to be able to handle following scenarios

  • all the 3 param's
  • 1 param
  • 2 param's

And i found this but still i got 404 when provide one query parameter, only works when all the parameters are given.

urls.py

re_path(r'^project_config/(?P<product>\w+|)/(?P<project_id>\w+|)/(?P<project_name>\w+|)/$',
            views.results, name='config')

And view

    def results(request, product, project_id, project_name):
        response = "You're looking at the results of question %s."
        print(product)
        print(project_name)
        return HttpResponse(response % project_id)

How can allow url to accept optional query parameters ?

pl-jay
  • 970
  • 1
  • 16
  • 33

1 Answers1

1

As mentioned in the comments using query-parameter try this

URL

re_path(r'^project_config/',views.results, name='config')

# http://127.0.0.1:8000/project_config/?product=1&project_id=2&project_name=foo

Views

def results(request):
    
    queryprms = request.GET
    product = queryprms.get('product')
    project_id = queryprms.get('project_id')
    project_name = queryprms.get('project_name')
    
    response = "You're looking at the results of question %s."
    
    # set your combination
    if product and project_id and project_name:
        # do some thing
    if product and project_id:
        # do some thing
    
    # so on

    return HttpResponse(response % project_id)
rahul.m
  • 5,572
  • 3
  • 23
  • 50