1

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.

4
  • 3
    Why do you consider request.GET.get('part') ugly? Commented Dec 11, 2019 at 14:15
  • Because every time when you add new variable you need to manually write similar code. It is place for bugs. Commented Dec 11, 2019 at 14:17
  • Nope, Django have possibility to prase url path, like path('get_part_info/<part>', views.get_part_info, name='get_part_info'), but in that case "part" can not contain any extra characters like slashes Commented Dec 11, 2019 at 14:21
  • You could initialize a args dict with the defaults and update it with request.GET. That way you keep all the defaults in one place at the top of your view. Commented Dec 11, 2019 at 14:23

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Daniel! Yea, this is nice and elegant solution.

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.