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?

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

You right! After read the thead stackoverflow.com/questions/3500859/django-request-get#3500932 I have more clear what you write me. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.