I want to know what is the best way to write in the URL.py
. I am trying to get the index in this way: www.example.com
with (r'',index)
. But when I try r''
, all pages in the website are going to the home page.
Part of my url.py
:
(r'^index',homepages),
(r'',homepages),
Thanks :)
The most basic technique to name Django urls is to add the name attribute to url definitions in urls.py . Listing 2-16 shows how to name a project's home page, as well as how to reference this url from a view method or template.
Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL, matching against path_info . Once one of the URL patterns matches, Django imports and calls the given view, which is a Python function (or a class-based view).
In Django 2.0, you use the path() method with path converters to capture URL parameters. path() always matches the complete path, so path('account/login/') is equivalent to url('^account/login/$') . The part in angle brackets ( <int:post_id> ) captures a URL parameter that is passed to a view.
Like this:
#...
(r'^$', index),
#...
Django URL matching is very powerful if not always as convenient as it could be. As Brian says, you need to use the pattern r'^$' to force your pattern to match the entire string. With r'', you are looking for an empty string anywhere in the URL, which is true for every URL.
Django URL patterns nearly always start with ^ and end with $. You could in theory do some fancy URL matching where strings found anywhere in the URL determined what view function to call, but it's hard to imagine a scenario.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With