marcoamorales
marcoamorales

Reputation: 623

Can you help me with Django's URL regex?

Currently, one of my urls is not working properly because I can't match it. I have the following entry in my urls.py

url(r'no_inventariado/nuevo/(?P<nombre>\S+)/(?P<serie>[a-zA-Z0-9_]*)/(?P<extension>\d{4})', 'inventario.views.nuevo_resguardo', name='nuevo_resguardo'),$ 

The problem seems to be in <nombre>. The url I'm using contains uppercase, lowercase and spaces in the <nombre> spot.

Ex.

http://127.0.0.1:8000/inventario/no_inventariado/nuevo/LUIS%20%20RICARDO%20DAVID%20P/XXXBX7399F11/7070/

How could I fix this? Any help is appreciated!

Upvotes: 0

Views: 2524

Answers (3)

Aligus
Aligus

Reputation: 1605

I made a simple test and it works on my machine:

from django.conf.urls import patterns, include, url
from django.http import HttpResponse

def hello(request, nombre):
    return HttpResponse('Hello: '+nombre)

urlpatterns = patterns('',
    url(r'^(?P<nombre>[a-zA-Z\s]*)/$', hello),
)

But it doesn't work with \S

Upvotes: 1

Eduardo Ivanec
Eduardo Ivanec

Reputation: 11862

\S should match all non-whitespace characters, but the %20s in your example are encoded spaces. I can't say for sure, but I'm guessing the whitespace is getting decoded before the GET request reaches the url handler. You can confirm this by testing with a name without spaces on it.

If this is the problem you can work around it by using a capture group like (?P<nombre>[^/]+) instead ("everything that is not a forward slash").

Upvotes: 2

stema
stema

Reputation: 93036

If you now allow \S+, means any non whitespace character, and you now want to add space then use .+?

url(r'no_inventariado/nuevo/(?P<nombre>.+?)/(?P<serie>[a-zA-Z0-9_]*)/(?P<extension>\d{4})>     'inventario.views.nuevo_resguardo', name='nuevo_resguardo'),$

The +? to have a non greedy match, means .+? will match every character till the next slash.

Upvotes: 2

Related Questions