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 ?

4
  • 6
    Would it not be better to use a GET parameter instead of putting them inside the url? Commented Mar 10, 2021 at 11:10
  • 1
    this will help you stackoverflow.com/a/14351174/5600452 Commented Mar 10, 2021 at 11:18
  • 2
    If the number of parameters is dynamic, then it is often better to work with a querystring instead. Commented Mar 10, 2021 at 11:23
  • parameters are not completely dynamic, it's a combination of three Commented Mar 10, 2021 at 11:27

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.