[Django]-Retrieve the integer stored in (?P<topic_id>\d+)

5👍

Your errors is not from ‘topic_id’, it’s about re.

If you use re.findall, it returns all list matched with your regex.

So in your case, the result of re.findall(r'topics/(?P<topic_id>\d+)/$', "topics/1/") will be ['1'].

So, of course, ['1'].topic_id raise AttributeError.

If you want to get group by 'topic_id', do like this

p = re.match(r'topics/(?P<topic_id>\d+)/$', "topics/1/")
p.group('topic_id') # it returns '1'

1👍

From the documentation:

re.findall(pattern, string, flags=0)
Return all non-overlapping
matches of pattern in string, as a list of strings.

You are trying to retrieve an attribute from a list, which that list does not have.

Leave a comment