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

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.

Related

Django: Reverse for 'delete' with arguments '(49,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['tidbit/delete_tidbit/']

Can't figure out how to solve this error
Here is the urls.py snippet:
urlpatterns = [
...
url(r'^delete_tidbit/', views.delete_tidbit, name='delete'),
...
]
The view:
def delete_tidbit(request, pk):
tidbit = Tidbit.objects.get(pk=pk)
tidbit.delete()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
And the portion of the template that raises this error:
<a href="{% url 'delete' tidbit.pk %}">
The issue is here:
url(r'^delete_tidbit/', views.delete_tidbit, name='delete'),
This URL doesn't accept an argument, where as you are trying to give it one.
Try this instead:
url(r'^delete_tidbit/(?P<pk>.*)', views.delete_tidbit, name='delete'),
But beware: you are accepting GET requests to delete items in your database, any crawler coming across those links may try to follow them and inadvertently delete your data. Consider using a GET that delivers a form to be POSTed to ensure an actual user is doing the action.

Django django-cms reverse 'NoReverseMatch at..' multisite language

This seems to be a "classic" problem :
NoReverseMatch at /tr/showroom/
Reverse for 'project-list' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
But the problem is, when I check the different topic on the internet and then my files, I don't get it.
So it's working perfectly on the native language. It happens when I try to change the language on this showroom page only.
Every page that have been copy with the commad cms copy works fine except this one.
Well, here is the model :
def get_slug(self):
return self.safe_translation_getter(
'slug',
language_code=get_language(),
any_language=False)
def get_absolute_url(self, current_app=None):
"""
Warning: Due to the use of django application instance namespace
(for handle multi instance of an application)we add the possibility
to use it with the reverse.
So if get_absolute_url is call without app instance it may failed (
for example in django_admin)
"""
lang = get_language()
if self.has_translation(lang):
kwargs = {'slug': self.get_slug()}
return reverse('djangocms_showroom:project-detail',
kwargs=kwargs,
current_app=current_app)
return reverse('djangocms_showroom:project-list', current_app=current_app)
def get_full_url(self, site_id=None):
return self._make_full_url(self.get_absolute_url(), site_id)
def _make_full_url(self, url, site_id=None):
if site_id is None:
site = Site.objects.get_current()
else:
site = Site.objects.get(pk=site_id)
return get_full_url(url, site)
The url :
from django.conf.urls import patterns, url
from .views import (ProjectListView, ProjectDetailView)
urlpatterns = patterns(
'',
url(r'^$', ProjectListView.as_view(), name='project-list'),
url(r'^project/(?P<slug>\w[-\w]*)/$', ProjectDetailView.as_view(), name='project-detail'),
)
And the html error :
Error during template rendering
In template /var/www/webapps/blippar_website/app/blippar/templates/djangocms_showroom/project_list.html, error at line 14
Which is :
<form id="projects-filter" action="{% url 'djangocms_showroom:project-list' %}">
Well, I am not very good yet with django and django-cms, if someone has any clue, it would be marvellous !

How do I pass parameters via url in 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
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

Redirect with HttpResponseRedirect to another function in python

I have a function :
def drawback(request,problem_id)
and I want in the end of this function to redirect to another page that is called from function
def show(request,problem_id)
I tried with
return HttpResponseRedirect(reverse('show',kwargs={'problem_id':10}))
return HttpResponseRedirect(reverse('show',kwargs={'problem_id':'10'}))
return HttpResponseRedirect(reverse('show',args=[10]))
return HttpResponseRedirect(reverse('show',args=(10))
Everything I found in other sites. But I receive the error
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'show' with arguments '()' and keyword arguments '{'problem_id': '10'}' not found.
or
Exception Value: Reverse for 'show' with arguments '(u'10',)' and keyword arguments '{}' not found.
This function and page works when I call it through html with a button. When I try to redirect from drawback function is not working.
urls.py
from django.conf.urls.defaults import *
from views import *
import settings
from django.conf import settings as rootsettings
urlpatterns = patterns('',
# authentication
(r'^start_auth', start_auth),
(r'^after_auth', after_auth),
# screens
(r'^problems/codelookup$', code_lookup),
# TESTING
(r'^problems/test$', test_message_send),
(r'^donnorsTool/$', problem_list),
(r'^problems/delete/(?P<problem_id>[^/]+)', archived_problem),
(r'^problems/edit/(?P<problem_id>[^/]+)', edit_problem),
(r'^problems/restore/(?P<problem_id>[^/]+)', restore_problem),
(r'^problems/new$', new_problem),
(r'^problems/archived$', archived_problems),
(r'^donnorsTool/show/(?P<problem_id>[^/]+)', show),
(r'^donnorsTool/consent/(?P<problem_id>[^/]+)/(?P<counter>[^/]+)', consent),
(r'^donnorsTool/withdraw/(?P<problem_id>[^/]+)/(?P<counter>[^/]+)', withdraw),
# static
## WARNING NOT FOR PRODUCTION
(r'^static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': rootsettings.SERVER_ROOT_DIR + settings.STATIC_HOME}),
)
Just call it like a function :
def drawback(request,problem_id)
...
...
return show(request,10)
From the docs, you can do several things.
# using the Python path
reverse('news.views.archive')
# using the named URL
reverse('news_archive')
# passing a callable object
from news import views
reverse(views.archive)
I prefer names in case you want to change out the name of the view easily, so
in urls.py
(r'^donnorsTool/show/(?P<problem_id>[^/]+)', show, name='show'),
in views.py
return HttpResponseRedirect(reverse('show',kwargs={'problem_id':10}))
I found a solution. I am not sure if it is the best but for me it worked like:
return HttpResponseRedirect('../../show/'+problem_id)
I don't know if it will cause any problems like that.

NoReverseMatch Exception in django named group url

I am new to django and playing with urls and stuck on this problem,
I have a view in my views.py which reverse url to a different view
def index(request):
username = request.session.get('username')
if username is None:
return HttpResponseRedirect(reverse('login_page'))
#return HttpResponse("Testing view session not found")
else:
return HttpResponseRedirect(reverse('profile_page', kwargs = {'username': username,}))
#return HttpResponse("Testing view " + username)
now when code will reach to else block since username is not None, so here is my URLconf
urlpatterns = patterns('',
url(r'(?P<username>^)', views.profile, name = "profile_page"),)
So in simple words I am calling profile_page url which is using a named parameter username and I am passing the same from kwargs, but I am getting NoReverseMatch with Exception Message:
Reverse for 'profile_page' with arguments '()' and keyword arguments '{'username': 'dheerendra'}' not found. 1 pattern(s) tried: ['user/(?P^)']
To construct a profile_page URL, it requires a username to be fully filled out. You're calling reverse('profile_page') without passing username in the kwargs.
Two things:
You've given the url a named group username but you haven't actually given a regular expression for the named group. You want your username regular expression to match a varying length username so you need:
url(r'?P<username>\w+)/$', views.profile, name="profile_page"),
where \w+ is the regular expression
Secondly, as you will see from the examlpe above, you need to terminate the regular expression with a $ so that urls such as /myusername/otherstring/ don't incorrectly get matched

Categories

Resources