Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass parameters via url in django?

Tags:

python

django

I am trying to pass a parameter to my view, but I keep getting this error:

NoReverseMatch at /pay/how

Reverse for 'pay_summary' with arguments '(False,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['pay/summary/$']

/pay/how is the current view that I'm at. (that is the current template that that view is returning).

urls.py

url(r'^pay/summary/$', views.pay_summary, name='pay_summary')

views.py

def pay_summary(req, option):
    if option:
        #do something
    else:
        #do something else
    ....

template

<a href="{% url 'pay_summary' False %}">my link</a>

EDIT

I want the view should accept a POST request, not GET.

like image 876
Saša Kalaba Avatar asked Sep 14 '15 14:09

Saša Kalaba


People also ask

How do you pass a value to a parameter in a 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.

Which method will pass the value via URL?

Submitting form values through GET method A web form when the method is set to GET method, it submits the values through URL. So we can use one form to generate an URL with variables and data by taking inputs from the users.

How does Django URL parameters and query strings work?

Django processes the query string automatically and makes its parameter/value pairs available to the view. No configuration required. The URL pattern refers to the base URL only, the query string is implicit. For normal Django style, however, you should put the id/slug in the base URL and not in the query string!


2 Answers

To add to the accepted answer, in Django 2.0 the url syntax has changed:

path('<int:key_id>/', views.myview, name='myname')

Or with regular expressions:

re_path(r'^(?P<key_id>[0-9])/$', views.myview, name='myname')
like image 60
Rexcirus Avatar answered Oct 18 '22 15:10

Rexcirus


You need to define a variable on the url. For example:

url(r'^pay/summary/(?P<value>\d+)/$', views.pay_summary, name='pay_summary')),

In this case you would be able to call pay/summary/0

It could be a string true/false by replacing \d+ to \s+, but you would need to interpret the string, which is not the best.

You can then use:

<a href="{% url 'pay_summary' value=0 %}">my link</a>
like image 33
Dric512 Avatar answered Oct 18 '22 15:10

Dric512