1

I was reading the thread Django optional url parameters And following the steps to generate a URL with a single optional parameter.

Well, my URL should be:

/client/
/client/?clientname=John

And I have defined two urlpatterns

url(r'^$', views.index, name='index'),
url(r'^/(?P<clientname>\d+)/',views.index),

Well, at this point both of them render the page. But, in my view:

def index(request, clientname='noparameter'):
    print("The searched name is: " + str(clientname))

The searched name is always noparameter

Am I doing something wrong?

Benjamin RD
  • 11,516
  • 14
  • 87
  • 157

2 Answers2

3

Url you are having is

/client/John/ 

instead of

/client/?clientname=John

also even in the following example using John will fail as your regex is for digits , check out more on topic of django dispatcher

  /client/4/ 

if you want to get GET parameters instead you can do that in view by using the following

request.GET.get('clientanme', None)
iklinac
  • 14,944
  • 4
  • 28
  • 30
2

It seems as though you are getting confused between a keyword argument and a get request. Using keyword arguments, which your urls.py is configured for, your view would like this:

def index(request, **kwargs):
    clientname = kwargs.get("clientname", "noparameter")
    print("The searched name is: " + str(clientname))

Your urls.py would also have to change to this for the url to this:

url(r'^client/(?P<clientname>\w+)/',views.index),

This could be called in the browser like:

/client/John
Kyle Higginson
  • 922
  • 6
  • 11
  • You right! After read the thead https://stackoverflow.com/questions/3500859/django-request-get#3500932 I have more clear what you write me. Thanks! – Benjamin RD Sep 24 '17 at 23:31