16

This is simple and obvious but I can't get it right:

I have the following view function declared in urls.py

 (r'^v1/(\d+)$', r'custom1.views.v1'),

originally I was passing a single parameter to the view function v1. I want to modify it to pass 2 parameters. How do I declare the entry in urls.py to take two parameters?

4 Answers 4

12

Supposing you want the URL to look like v1/17/18 and obtain the two parameters 17 and 18, you can just declare the pattern as:

(r'^v1/(\d+)/(\d+)$', r'custom1.views.v1'),

Make sure v1 accepts two arguments in addition to the request object:

def v1 ( request, a, b ):
    # for URL 'v1/17/18', a == '17' and b == '18'.
    pass

The first example in the documentation about the URL dispatcher contains several patterns, the last of which take 2 and 3 parameters.

Sign up to request clarification or add additional context in comments.

Comments

12

Somewhere along the line I got in the habit of naming them directly in the regex, although honestly I don't know if it makes a difference.

#urls:
(r'^v1/(?P<variable_a>(\d+))/(?P<variable_b>(\d+))/$', r'custom1.views.v1')

#views:
def v1(request, variable_a, variable_b):
    pass

Also, it's very Django to end the url with a trailing slash - Django Design Philosophy, FYI

Comments

8

I believe each group in the regex is passed as a parameter (and you can name them if you want):

(r'^v1/(\d+)/(\d+)/$', r'custom1.views.v1')

Check out the examples at: https://docs.djangoproject.com/en/dev/topics/http/urls/. You can also name your groups.

Comments

6

in django 2.x and 3.x:

url:

    path("courses/<slug:param1>/<slug:param2>", views.view_funct, name="double_slug")

template:

    <a href="{% url 'double_slug' param1 param2 %}">Click {{param2}}!</a>

2 Comments

Do the 2 parameters have to be separated by a slash? Could you have something like: http://example.com/courses?start=01-01-2012&end=01-31-2012 . Although i don't know what the URLconf would look like.
@moonraker yes you can do so, but I guess it's a convention to use slashes

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.