1

I am trying to implement a regex url for these examples:

localhost:8000/curvas?parcela=298

or

localhost:8000/curvas?parcela=7&fk_fecha=234

I tried implementing a similar url regex from django rest framework (documentation) with the following regex path:

re_path(r'curvas(?P<parcela>.+)', views.CurvasFilter.as_view()),

And it works but it is too permisive, for example that url also match the regex:

localhost:8000/curvas?random=298

How can I change the regex to match only the desired url params?

1
  • parcela is part of the querystring, not the path, hence you can not capture this with url(..), re_path(..) or path(..). Commented Dec 10, 2019 at 15:27

1 Answer 1

2

The part after the question mark (?) is the querystring [wiki]. It is not part of the path, and thus you can not capture it with path(..) or re_path(..). It would furthermore likely not be a good idea anyway, since often the order of the parameters is random, and thus a regex that matches ?foo=4&bar=2 might have difficulty with ?bar=2&foo=4.

The path is thus:

re_path(r'^curvas/$', views.CurvasFilter.as_view())

You can access the value for parcela with self.request.GET['parcela']. For example:

class CurvasFilter(ListView):
    model = Curvas

    def get_queryset(self):
        return super().get_queryset().filter(
            parcela=self.request.GET['parcela']
        )
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, so I will use the following regex: r'^curvas?$' which seems more restrictive, isn't it? (it also requires to the url to have the question mark)
@David1212k: no the question mark is not part of the path either, it should be ^curvas/$ (or ^curvas$, so without the question mark). Note that here the question mark is by the way interpreted as a regular expression quantifier ("zero or one").

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.