How do I pass parameters via url in django? - python

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
my link
EDIT
I want the view should accept a POST request, not GET.

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')

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:
my link

Related

Making URL to accept parameters as optional. Non Capturing

I want to make my url to accept the optional parameters only when given. I am unable to make the parameters optional/non-capturing.
re_path(r'^users/(?:(?P<sort_by>\d+)/)?$', views.UserListView.as_view(), name='user_list'),
I want this url to accept a slug field only when provided to the view. How can I do this?
It is showing an error
Reverse for 'user_list' with keyword arguments '{'sort_by': 'username'}' not found. 1 pattern(s) tried: ['admin/users/(?:(?P<sort_by>\\d+)/)?$']
when I passed sort_by='username'
You could keep your url to:
re_path(r'^users/$', views.UserListView.as_view(), name='user_list'),
And then in your template use
Sort
I would create 2 URLs:
path('users/<str:sort_by>', views.UserListView.as_view(), name='user_list_by_user'),
path('users', views.UserListView.as_view(), {'sort_by': 'default_sort_you_use'}, name='user_list'),
Then you can call the appropriate URL and always have a sort_by value in the view.

Passing multiple arguments from django template href link to view

I am trying to pass some arguments with a link url href in a template to a view.
In my template :
Print
So i am trying to pass 4 arguments to my view.
My view is :
def print_permission_document(request, studentname, studentsurname, studentclass, doctype):
file_write(studentname.encode('utf-8')+" "+studentsurname.encode('utf-8')+" "+studentclass+" "+doctype)
return response
My urls.py is :
url(r'^print-permission-document/.+$', print_permission_document, name='print-permission-document')
But i get below error :
Exception Type: TypeError
Exception Value:
print_permission_document() takes exactly 5 arguments (1 given)
This is not how you specify multiple parameters in a URL, typically you write these in the URL, like:
url(
r'^print-permission-document/(?P<studentname>\w+)/(?P<studentsurname>\w+)/(?P<studentclass>\w+)/(?P<doctype>[\w-]+)/$',
print_permission_document, name='print-permission-document'
)
Then you generate the corresponding URL with:
Print
This will then generate a URL that looks like:
/print-permission-document/somename/someclass/doctype-studentlatepermission
Typically a path does not contain key-value pairs, and if it does, you will need to "decode" these yourself.
You can also generate a querystring (after the question mark), these you can then access in request.GET [Django-doc].
You are passing your URL wrongly. and URL in template is also declared wrongly.
Try this
Print
url(
r'^print-permission-document/(?P<studentname>\w+)/(?P<studentsurname>\w+)/(?P<studentclass>\w+)/(?P<doctype>\w+)/$',
print_permission_document, name='print-permission-document'
)
I had the same error , i corrected it by :
url(r'^auth_app/remove_user/(?P<username2>[-\w]+)/$', views.remove_user, name="remove_user"),
Use this pattern for passing string
(?P<username2>[-\w]+)
This for interger value
(?P<user_id>[0-9]+)

Django: reverse() does not find view with args/kwargs given

There are a few posts related to my problem. However, none seems to solve the following issue:
I have defined urls in myapp/urls.py:
app_name = "myapp"
urlpatterns=[
url(r'^$', views.index, name="index"),
url(r'^adduser/$', views.addUser, name="adduser"),
]
and corresponding views in myapp/views.py:
def index(request, status_msg=None, error_msg=None):
return HttpResponse(render(request, "myapp/index.html",
context={"error_message":error_msg, "status_message":status_msg}))
def addUser(request):
try:
uname=request.POST["user_name"]
except KeyError:
url = reverse("myapp:index", args=(None, "No user name specified."))
return HttpResponseRedirect(url)
# ... adding user to db ...
url = reverse("myapp:index", args=("Added user '%s'"%uname,))
return HttpResponseRedirect(url)
Either variant of passing arguments to index() from the redirect in addUser() yields an error of the kind
Reverse for 'index' with arguments '(None, u'No user name specified.')' not found. 1 pattern(s) tried: [u'myapp/$']
I don't get what I'm doing wrong here. Seems the index view is found but not recognized to allow any arguments aside the request?
Using kwargs instead of args does not help, either.
Any suggestions are highly appreciated. Thanks already!
Your URL doesn't seem to support arguments (i.e captured groups in the regex). Therefore you should be using just:
reverse("myapp:index")
Check the docs for the reverse() function here.

Django : NoReverseMatch for HttpResponseRedirect with kwargs

I'm getting the following error:
NoReverseMatch at /updatebooking/
Reverse for 'common.views.myview'
with arguments '()' and keyword arguments '{'msg': "hello", 'case':
'success'}' not found.
common/views.py
def view1(request):
...
return HttpResponseRedirect(reverse('common.views.view2', kwargs= {"msg":"hello","case":"success"}))
def view2(request,msg=None,case=None):
...
urls.py
url(r'^test1/$','common.views.view1',name='my_view1'),
url(r'^test2/$','common.views.view2',name='my_view2'),
This line reverse('common.views.view2', kwargs= {"msg":"hello","case":"success"}) is throwing the error.
The error comes only when I use kwargs. Following codes work:
return HttpResponseRedirect(reverse('my_view2'))
return HttpResponseRedirect(reverse('common.views.view2'))
Kindly help me resolve this.
When you are using reverse with kwargs parameters django tries to find a parameterized url route. In your example, matching route would be similar to
url(r'^test2/(?P<msg>\w+)/(?P<case>\w+)$','common.views.view2',name='my_view2')
Refer to reverse and URLDispatcher documentation for more details. Unfortunately, both URLDispatcher and reverse manuals are a little bit cryptic about this particuar feature.
Your url doesn't have msg or case parameter, that's why Django can't find it. See the paramenter slugin this example:
url(r'^(?P<slug>[^/]+)/$', 'test.views.detail', name="test-detail")
I believe that you're trying to pass a message/notification to another view. If that's the case, you should check the messages framework.

NoReverseMatch django error multiple URLs same method

error message:
ExceptionType: NoReverseMatch
Exception Value: Reverse for 'darts.teams.views.expanded_details' with arguments '(u'RightFlights',)' and keyword arguments '{}' not found.
in the template:
Expanded Details
in urls.py
urlpatterns = patterns('darts.teams.views',
url(r'^(?P<teamname>.*?)/expanded_details/$', 'team_details', {'expanded': True}, "expanded_details"),
url(r'^(?P<teamname>.*?)/details/$', 'team_details', name="team_details"),
url(r'^(?P<teamname>.*?)/add_player/$', 'team_add_player', name="team_add_player"),
url(r'^(?P<teamname>.*?)/add_player/confirm/$', 'team_add_player',"team_add_player_confirm"),
)
The additional URLs in urls.py all render fine, but the 'expanded_details' one is throwing the error.
Why is this one different than the others? Am I missing something blatant?
update
The error says "Reverse for 'darts.teams.views.expanded_details' failed", but it should be 'darts.teams.views.team_details' or 'expanded_details'. The first form is the path to view, the latter is the name of the named URL.
You could check the value of expanded_details inside the templatetag to ensure it is resolved to one of the correct values above, or follow slackjake's suggestion: use 'expanded_details' (note the single quote) directly.
(?P<teamname>.*? is invalid, maybe you mean (?P<teamname>.*?)?
Also, what does lib.url do?

Categories

Resources