[Answered ]-Python Django named vs positional arguments for url routing

2👍

To answer your question, flavor_detail will accept four arguments (in order) and one keyword argument. The regexp in url will pass the matches it finds in order, but as you’ve also defined a keyword for each arg it will instead pass a kwarg dictionary. As you’ve kept the variable names consistent this dict will pass the correct args in the correct place (if you had used different variable names this would not have worked). You can avoid this ‘magic’ by simply specifying keyword arguments for flavors_detail as described below.

Your url is a regular expression which defines them:

 ?P<content_type>

will produce the kwarg content_type. Check out the re module in python (docs).

(?P<name>...)
Similar to regular parentheses, but the substring matched by the group is accessible within the rest of the regular expression via the symbolic group name name. Group names must be valid Python identifiers, and each group name must be defined only once within a regular expression. A symbolic group is also a numbered group, just as if the group were not named. So the group named id in the example below can also be referenced as the numbered group 1.

As you are defining your variables as keyword args kwargs you could to change your view declaration to accept kwargs:

def flavors_detail(request, slug=slug, asset_id=asset_id, content_type=content_type, format="html"):

However, Python will also accept your previous definition (my comment was premature), so long as you’re careful to preserve the argument order! There is more information on how this happend here – to quote

If keyword arguments are present, they are first converted to positional arguments

Leave a comment