Isador
Isador

Reputation: 603

How to pass a variable to urls.py

I have a database 'artist' with one table : 'name', 'style'. Users can add any names for an artist.

I would like to pass an argument to url in my template, like this :

<a href="{% url 'webgui.views.music' artist.name %}" style="margin-bottom: 3px" type="button"

But is it possible to set dynamically the URL with the argument 'artist.name' (in urls.py) ?

My urls.py actually :

url(r'^music/(\d+)/$', 'webgui.views.music'),

Maybe I need to change '\d+' by another regexp ??

Upvotes: 1

Views: 93

Answers (1)

gcerar
gcerar

Reputation: 988

Instead of using

url(r'^music/(\d+)/$', 'webgui.views.music'),

because d+ stands for digits, you should use

url(r'^music/?P<artist_name>[a-zA-Z0-9 \'&-]/$', 'webgui.views.music')

Don't forget to modify function

def whatever_named_it(request, artist_name):
    ...

Update: In template you should use

{% url 'webgui.views.music' artist_name=artist.name %}

because we are using named arguments.

Extra: If you are going to allow any text for artist's name, I would recommend you using slug to avoid spaces in URL. That would make it better to read, search engine friendly and avoid of insane user input. When programming web-app never trust user input ... ever.

For "slugified" name urls would be:

url(r'^music/(?P<slug>[\w-]+)/$', 'webgui.views.music')

Upvotes: 3

Related Questions