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.
Related
I got a No reverseMatch Error evnthough pk has been imported.
Traceback:
Reverse for 'profile_page' with no arguments not found. 1 pattern(s) tried: ['profile_page/(?P<pro>[^/]+)$']
urls.py:
path('profile_page/<str:pro>', UserProfileView, name='profile_page'),
Reverse for 'profile_page' with no arguments not found. 1 pattern(s) tried: ['profile_page/(?P<pro>[^/]+)$']
Your Error Traceback clearly says that no arguments are found for profile_page route.
Since your url route for profile_page accepts a string, you need to pass one
urls.py
path('profile_page/<str:pro>', UserProfileView, name='profile_page'),
Wherever you are navigating to profile_page in your HTML code. you have to pass a string along with it.
I suppose you are using this route to display the profile page of a user, then use this - {% url 'profile_page' <some_user_name> %}
Eg: User
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]+)
I call a specific url from and ajax function which will calls the respective view function. In view function I want to redirect the page by calling another view (because I can't render after ajax request).
Here are my urls:
urlpatterns = [
url(r'^$', views.search, name='search'),
url(r'^search_result/.+$', views.search_result, name='search_result'),
url(r'^new_search_result/$',
views.new_search_result,
kwargs={'selected': '', 'keyword': ''},
name='new_search_result')
]
And here is the search_result view:
#csrf_exempt
def search_result(request):
keyword = request.POST.get('keyword')
selected = request.POST.get('selected')
url = reverse('new_search_result',
kwargs={'keyword': keyword,
'selected': selected})
return HttpResponseRedirect(url)
# return render(request, 'SearchEngine/search_result.html', {'all_results': result})
And here is the new_search_result view:
def new_search_result(request, selected={}, keyword=''):
# code blocks
But in consul I get this error:
django.urls.exceptions.NoReverseMatch: Reverse for 'new_search_result' with keyword arguments '{'selected': '{"PANTHER":"ftp.pantherdb.org","Pasteur Insitute":"ftp.pasteur.fr","Rat Genome Database":"ftp.rgd.mcw.edu"}', 'keyword': 'dfasdf'}' not found. 1 pattern(s) tried: ['searchengine/new_search_result/$']
[22/Jul/2017 12:52:12] "POST /searchengine/search_result/dfasdf HTTP/1.1" 500 16814
The kwargs argument to url
The extra kwargs argument you provide to the call to url allows you to define extra parameters that are then passed on to the view. They do not define extra arguments that are provided when fetching the url - the call to reverse does not know about these extra arguments, the call to reverse only knows about the arguments defined in the url pattern.
So if you have:
urlpatterns = [
url(r'^blog/(?P<year>[0-9]{4})/$', myview,
kwargs={'foo': 'bar'}),
]
This means that when your url is fetched as blog/1111 then view myview is invoked with two parameters: year with value 1111 and foo with value bar.
Only the view sees the extra argument foo - it is not in the url, and it is not provided to the reverse function. The kwargs argument of the reverse function actually refers to the arguments defined in the url pattern.
Passing parameters to a view
So looking at what you're trying to achieve: you want to redirect the user's browser to a different URL, such that the resulting view will have access to the keyword and selected parameters.
If you wanted that data to be hidden from the user, you would have to store it in the session. Assuming this is not the case you have three ways to pass parameters to a view: via GET parameters, via POST data and view the url. In your case as you're redirecting to another page, you can't use a POST request. You could use the url but for a search page I would think the best option would be to use GET parameters.
So in your search_result view you could add a query string to the URL ie. ?keyword=...&selected=.... For example:
import urllib
#csrf_exempt
def search_result(request):
args = {
'keyword': request.POST.get('keyword'),
'selected': request.POST.get('selected')
}
url = '%s?%s' % (
reverse('new_search_result'),
urllib.urlencode(args)
)
return HttpResponseRedirect(url)
And your new_search_result view would read those from the request:
def new_search_result(request):
selected = request.GET.get('selected')
keyword = request.GET.get('keyword')
# ...
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
I'm running into an issue with supplying captured URL parameters through template tags. I have a URL dispatch with a captured parameter that hands off to another URL dispatch with include() that does not have any captured parameters:
nodemanager.urls:
url(r'^(?P<node_id>\d+)/rank/', include('ranking.urls')),
ranking.urls:
url(r'^setup$', views.setup, name='setup'),
I am using {% url 'setup' node_id=node.id %} in my template which creates the error:
TypeError at /stage1/node/5/rank/setup
setup() got an unexpected keyword argument 'node_id'
If I take out the keyword argument and just use: {% url 'setup' %}, the landing page fails to load and I get the (predictable) error:
NoReverseMatch at /stage1/
Reverse for 'setup' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) >tried: ['stage1/node/(?P\d+)/rank/setup$']
I know that I need to supply the parameter for node_id to properly reverse the URL. However, the named url "setup" in my ranking app doesn't take any parameters, but the URL that includes it (in the nodemanager app) does.
How would I properly pass the node_id keyword argument using a template tag that points to stage1/node/5/rank/setup, i.e. something of the form {% url 'setup' ... %}. Can I do this?
Let me know if I need to post more context code; I tried to include (what I thought) are the relevant parts.
The original error is not due to the URL reversing, but comes when the view is actually called. This is probably because you have not declared it to take a node_id argument. It should be like this:
def setup(request, node_id):
...
Once you've fixed that, the original url tag syntax should work.