Python Forum

Full Version: url pattern matching
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
My url pattern is /music/712/ which I can match using path('music/<int:album_id>/', views.detail, name='detail')

But how do I tailor it to match url pattern that strictly has 2 digits and not 3 digits i.e. /music/41/
I think, you are supposed to query the db with whatever id supplied in the request (of course, assuming you properly handle the risk of SQL injections), e.g. 712 and if no record returned from the DB, display appropriate message. what if in the future you have more than 99 records? how do you deal with id in range 1-9 if you strictly want 2 digits? of course if you insist on checking the param you can do it before actually querying the DB, but I don't think it's the best idea

What fremeowork do you use? If there is something specific...
I am new to Django and currently learning.
My initial question was just out of curiosity.
I am using Django 2.2.7
However, I was learning from youtube videos and they were pattern matching using regular expressions and when I tried to do the same, I realised my version of Django didn't allow r' component for regular expression.
Anyways, I just wanted to know is there a way (in later versions of Django) to define how many digits there are in your url string? You can easily do it in ealier versions of django using regular expressions by using stuff like [0-9]{2} for 2 digits or [0-9]{3} for 3 digits but how can you specify such conciseness in later versions of Django that don't allow regular expressions?
i will leave the answer to someone with more experience in Django. My initial response may not be best course of action after all
You can use django.urls.re_path() in Django 2 or 3 for more complex regex calls.
This is alias to old url(regex, view, kwargs=None, name=None)
from django.urls import include, re_path

re_path(r"music/\d{2}", views.detail, name='detail')
Then use path for simpler lookups.
that's exactly what I was looking for.