Aleksandr Beliavski
Aleksandr Beliavski

Reputation: 141

Django reqired parameters in url query

Is there any chances to specify which parameters are required in url query and automatically pass them into view function?

In urls.py I would like to have something like this:

path('get_part_info?<part>', views.get_part_info, name='get_part_info'),

And in views.py to have something like this:

def get_part_info(request, part):
    # do something with part
    return JsonResponse({'result': part})

Idea is to avoid ugly construction like: part= request.GET.get('part')

URL path is not a solution, because "part" value can have various extra characters like slashes etc.

Upvotes: 1

Views: 59

Answers (1)

Daniel Hepper
Daniel Hepper

Reputation: 29967

You can write a decorator:

from functools import wraps
from django.http import HttpResponseBadRequest, JsonResponse

def query_params(*param_names):
    def decorator(func):
        @wraps(func)
        def inner(request, *args, **kwargs):
            try:
                params = {name: request.GET[name] for name in param_names}
            except KeyError:
                return HttpResponseBadRequest("Missing Parameter")
            kwargs.update(params)
            return func(request, *args, **kwargs)

        return inner

    return decorator


@query_params("part")
def get_part_info(request, part):
    # do something with part
    return JsonResponse({"result": part})

This decorator returns a 400 if a parameter is missing, but that could be changed any way you want, for example, redirect to another URL or to use default values.

Upvotes: 1

Related Questions