user5674825
user5674825

Reputation:

Django URL issue with regular expressions

I am new to Python, Django 1.9 and overall regular expressions. So I am trying to write something like this within urls.py

search/doc_name/language/?id
  1. where doc_name, allow for any name/case/length etc. like so: 'My Fave Doc 12'
  2. where language, allow two letters like so: 'en'
  3. where id, allows only numbers.

This is what I have, can someone point out where I went wrong?

url(r'^search/[\w-]+/[a-z]{2}+/(?P<id>[0-9]+)$', '....

Upvotes: 0

Views: 289

Answers (2)

Dhia
Dhia

Reputation: 10609

You should really avoid to have spaces in you URL, I suggest the following:

url format: /search/<doc_name>/<id>/?lang=<language>

in urls.py:

url(r'^search/(?P<doc_name>[\w]+)/(?P<id>[0-9]+)/$'), your_view)

in views.py:

lang = request.GET.get('lang', 'en')
doc_name = request.POST.get('doc_name')
id = request.POST.get('id')

Upvotes: 0

ndnenkov
ndnenkov

Reputation: 36101

The doc_name doesn't allow spaces. Add a space in the character set if you want one. Make sure you put it before the dash ([\w -]+). If other whitespaces are allowed, used \s instead ([\w\s-]+).

Also the language would currently match any even amount of letters. Remove the + and leave only [a-z]{2}. + means repeat one or more times, anything is matched only once by default.

Upvotes: 2

Related Questions