URL with args does not reverse - django

I have the following url:
urlpatterns += patterns('app_common.views_settings',
url(r'([\w-]+)/(\d+)/settings/$', 'settings', name="configuration_homepage"),
url(r'(?P<short_name>[\w-]+)/(?P<product_id>\d+)/settings/modify/(?P<sim_id>\d+)/$', 'modify_sim', name="modify_sim"),
)
urlpatterns += patterns('app_common.views_operator',
url(r'^operator/$', 'choose_operator', name="choose_operator"),
url(r'^(?P<short_name>[\w-]+)/project/$', 'choose_project', name="choose_project"),
url(r'([\w-]+)/(\d+)/$', 'set_product', name="set_product"),
url(r'^(?P<short_name>[\w-]+)/$', 'set_operator', name="set_operator"),
)
I tried to reverse configuration homepage using:
url = reverse('configuration_homepage', kwargs={short_name, product_id})
return HttpResponseRedirect(url)
Some times it works, but other times if failed with this issue (short_name=OCI and product_id=1)
Exception Type: NoReverseMatch
Exception Value: Reverse for 'configuration_homepage' with arguments '(u'1', u'OCI')' and keyword arguments '{}' not found.
If you guys detect something wrong in my code fell free to tell me... I tried to give name to variable but urls are not found in that case.

Use args instead of kwargs,
url = reverse('configuration_homepage', args=[short_name, product_id])

Your kwargs is wrong, you are passing a set() instead of a dict()
What you (probably) want is:
url = reverse('configuration_homepage',
kwargs={short_name: short_name, product_id: product_id})
This is one of the many reasons why I prefer dict(a=1, b=2) over {a:1, b:2} when possible,

Related

Django NoReverseMatch at

I have the following URLs:
url(r'^%sdform/' %(URLPREFIX), pv.dform, name='dform'),
url(r'^%sform/(P?<growl>.*)/' %(URLPREFIX), pv.dform, name='dform'),
The view code:
def dform(request, growl = None) is the method signature
The redirect code:
msg = 'test'
return redirect('dform', growl=msg)
Any idea why I get that error? I'm sending the right parameter to the right view method with the right argument name and all that.
EDIT:
Based on the answer below, I tried:
url(r'^%sdform/(P?<growl>.*)/' %(URLPREFIX), pv.dform, name='dform_message')
And changed the redirect to:
return redirect('dform_message', growl='Updated Settings')
I still get NoReverseMatch
I think your problem is that you shall not use the same names for different urls (django docu).

NoReverseMatch exception - redirect with keyword arguments

I am getting a NoReverseMatch error when trying to use Django's redirect, and cannot figure out what I am doing wrong.
In views:
def addConjugatedForm(request):
#update database
return redirect('findConjugatedForms', chapter=ch.chapter, verse=verse.verse, book=b.name)
def findConjugatedForms(request, book, chapter, verse):
#return a view
In urls.py:
url(r'^findConjugatedForms/(?P<book>\w+)/(?P<chapter>\d+)/(?P<verse>\d+)/', 'findConjugatedForms'),
The url works as a url, i.e. "...findConjugatedForms/Romans/3/24" returns a page. But when a form on that page is submitted, it won't redirect back.
I have named arguments in my url (which seems to be the common problem in other questions on Stack Overflow) and the values of the kwargs seem to be correct.
Reverse for 'findConjugatedForms' with arguments '()' and keyword arguments '{'chapter': 3, 'verse': 24, 'book': u'Romans'}' not found. 0 pattern(s) tried: []
What am I missing?
redirect uses reverse internally. You need to define a viewname for the url, or use a Python path or pass a callable object:
url(r'^findConjugatedForms/(?P<book>\w+)/(?P<chapter>\d+)/(?P<verse>\d+)/',
'findConjugatedForms',
name='findConjugatedForms') # Define a name
Besides, add a suffix '$' into the pattern to prevent the url from matching other urls that starts with findConjugatedForms/book/chapter/verse/

Django URL Conf For Keyword Argument

What's wrong with the URL conf below:
url(
r'^outgoing-recommendations(?P<entry>\w+)/$',
login_required(outgoing_messages),
name='outgoing-recommendations',
),
Here is the invocation:
return redirect('outgoing-recommendations', kwargs={'entry':'outgoing'})
Here is the view function:
def outgoing_messages(request,entry):
user = User.objects.get(pk=request.session['user_id'])
I'm getting the error below:
Reverse for 'outgoing-recommendations' with arguments '()' and keyword arguments '{'kwargs': {'entry': 'outgoing'}}' not found.
The URL should look like this
url(r'^outgoing-recommendations/(?P<entry>\w+)/$',login_required(outgoing_messages), name='outgoing-recommendations'),
So you forgot your / on outgoing-recommendations.
Also you should call your redirect like this
return redirect('outgoing-recommendations', entry='outgoing')
and leave off the kwargs={} part, because what's happening is that you're trying to send in the keyworded arguments kwargs with it's nested kwargs.
But what I think you actually want is this
return redirect(reverse('outgoing-recommendations', kwargs={'entry':'outgoing'}))

Reverse for '' with arguments and keyword arguments '' not found

I have following views in my light_shop app:
def order_list(request, error_message):
context = {}
context['type'] = 'order-list'
context['error_message'] = error_message
update_context(request, context, add_order_list=True)
return render(request, 'light_shop/order_list.html', context)
def add_to_list(request, prd_id):
add_product_to_list(request, prd_id)
return HttpResponseRedirect(reverse('light_shop.views.order_list', args=('test_error',)))
and this is urls.py
urlpatterns = patterns('light_shop',
...
url(r'^add-to-list/(?P<prd_id>\d+)/$', 'views.add_to_list'),
url(r'^show-list/()$', 'views.order_list'),
...
)
but I get error: Reverse for 'light_shop.views.order_list' with arguments '('test_error',)' and keyword arguments '{}' not found. in add_to_list second line.
I even test naming parameter in url pattern for order_list. (e.g. url(r'^show-list/(?P<error_message>)$', 'views.order_list') and changing reverse function to reverse('light_shop.views.order_list', kwargs={'error_message':'error_message'})) but again same error is occurred.
I'm using Django 1.5 and I look this page for documantation and I am really confused what is the problem:
https://docs.djangoproject.com/en/1.5/topics/http/urls/
The problem is with the URL pattern
url(r'^show-list/()$', 'views.order_list'),
which seems to be incomplete.
Update it to (Basically, specify a Named Group)
url(r'^show-list/(?P<error_message>[\w_-]+)$', 'views.order_list'),

Reverse Not Found: Sending Request Context in from templates

N.B This question has been significantly edited before the first answer was given.
Hi,
I'm fairly new to django, so apologies if I'm missing something obvious.
I've got a urls.py file that looks like this:
urlpatterns = patterns(
'',
(r'^$', 'faros.lantern.views.home_page'),
(r'^login/$', 'django.contrib.auth.views.login'),
(r'^logout/$', 'django.contrib.auth.views.logout'),
(r'^about/$', 'faros.lantern.views.about_page_index', {}, 'about_page_index'),
(r'^about/(?P<page_id>([a-z0-9]+/)?)$', 'faros.lantern.views.about_page', {}, 'about_page'),
)
Views that looks like this:
def about_page_index(request):
try:
return render_to_response('lantern/about/index.html', context_instance=RequestContext(request))
except TemplateDoesNotExist:
raise Http404
def about_page(request, page_id):
page_id = page_id.strip('/ ')
try:
return render_to_response('lantern/about/' + page_id + '.html', context_instance=RequestContext(request))
except TemplateDoesNotExist:
raise Http404
And a template that includes this:
Contact
Contact
I'm getting this error message:
Caught an exception while rendering: Reverse for '<function about_page at 0x015EE730>' with arguments '()' and keyword arguments '{'page_id': u'contact'}' not found. The first reverse works fine (about_page_index), generating the correct URL without error messages.
I think this is because the request argument to the about_page view (request) is used, so I need to pass it in when I generate the URL in my template. Problem is, I don't know how to get to it, and searching around isn't getting me anywhere. Any ideas?
Thanks,
Dom
p.s. As an aside, does that method of handling static "about" type pages in an app look horrific or reasonable? I'm essentially taking URLs and assuming the path to the template is whatever comes after the about/ bit. This means I can make the static pages look like part of the app, so the user can jump into the about section and then right back to where they came from. Comments/Feedback on whether this is djangoic or stupid appreciated!
If I guess correctly from the signature of your view function (def about_page(request, page_id = None):), you likely have another URL configuration that points to the same view but that does not take a page_id parameter. If so, the django reverse function will see only one of these, and it's probably seeing the one without the named page_id regex pattern. This is a pretty common gotcha with reverse! :-)
To get around this, assign a name to each of the url patterns (see Syntax of the urlpatterns variable). In the case of your example, you'd do:
(r'^about/(?P<page_id>([a-z]+/)?)$', 'faros.lantern.views.about_page',
{}, 'about_with_page_id')
and then in the template:
Contact
Edit
Thanks for posting the updated urls.py. In the url template tag, using the unqualified pattern name should do the trick (note that I'm deleting the lantern.views part:
Contact
Contact
Edit2
I'm sorry I didn't twig to this earlier. Your pattern is expressed in a way that django can't reverse, and this is what causes the mismatch. Instead of:
r'^about/(?P<page_id>([a-z]+/)?)$'
use:
r'^about/(?P<page_id>[a-z0-9]+)/$'
I created a dummy project on my system that matched yours, reproduced the error, and inserted this correction to success. If this doesn't solve your problem, I'm going to eat my hat! :-)