Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django url pattern - string parameter

Django url pattern that have a number parameter is:

url(r'^polls/(?P<poll_id>\d+)/$', 'polls.views.detail') 

What will be the correct syntax if my poll_id is not a number but a string of character?

like image 384
rechie Avatar asked Aug 10 '12 03:08

rechie


People also ask

How do I pass URL parameters in Django?

Django URL pass parameter to view You can pass a URL parameter from the URL to a view using a path converter. Then “products” will be the URL endpoint. A path converter defines which type of data will a parameter store. You can compare path converters with data types.

How does Django treat a request URL string?

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).


2 Answers

In newer versions of Django such as 2.1 you can use

path('polls/<str:poll_id>', views.polls_detail) 

as given here Django URL dispatcher

def polls_detail(request,poll_id): #process your request here 
like image 27
abhijeetgurle Avatar answered Oct 23 '22 09:10

abhijeetgurle


for having a string parameter in url you can have: url like this:

url(r'^polls/(?P<string>[\w\-]+)/$','polls.views.detail') 

This will even allow the slug strings to pass eg:strings like node-js etc.

like image 143
Hiro Avatar answered Oct 23 '22 09:10

Hiro