Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django url patterns with 2 parameters

Tags:

django

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?

like image 790
afshin Avatar asked Jul 05 '11 19:07

afshin


People also ask

How do I pass multiple parameters in URL?

To add a parameter to the URL, add a /#/? to the end, followed by the parameter name, an equal sign (=), and the value of the parameter. You can add multiple parameters by including an ampersand (&) between each one.

How do I create URL patterns in Django?

Here's an example URLconf and view: # URLconf from django.urls import path from . import views urlpatterns = [ path('blog/', views.page), path('blog/page<int:num>/', views.page), ] # View (in blog/views.py) def page(request, num=1): # Output the appropriate page of blog entries, according to num. ...

What is the difference between path and URL in Django?

In Django 2.0, you use the path() method with path converters to capture URL parameters. path() always matches the complete path, so path('account/login/') is equivalent to url('^account/login/$') . The part in angle brackets ( <int:post_id> ) captures a URL parameter that is passed to a view.


2 Answers

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.

like image 198
André Caron Avatar answered Sep 22 '22 18:09

André Caron


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

like image 25
j_syk Avatar answered Sep 21 '22 18:09

j_syk