Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
url pattern matching
#1
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/
Reply
#2
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...
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
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?
Reply
#4
i will leave the answer to someone with more experience in Django. My initial response may not be best course of action after all
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
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)
Example.
from django.urls import include, re_path

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


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020