Getting another error in Django: Caught NoReverseMatch error in django - python

I seem to have another problem with passing parameters in Django. I seem to get a Caught NoReverseMatch error.
Caught NoReverseMatch while rendering: Reverse for 'tiptop.views.service_order2' with arguments '('', 17L, 1)' and keyword arguments '{}' not found
It reaches the client_id and service_type but not the order_no. I am not so sure what is wrong but it complains of the order.pk argument.
#urls
(r'^quote/service_order/(?P<client_id>\d+)/(?P<order_no>\d+)/(?P<request_type>\d+)/$', views.service_order2),
#views.py
def service_order2(request, client_id = 0, order_no = 0, request_type = 1):
# A lot of code
order=request.session['order']
return render_to_response('service_step1__2nd.html', {'contacts':contacts, 'addresses':addresses, 'title':title, 'service_list':service_list, 'date_type':date_type, 'address_type':address_type, 'order':order}, context_instance = RequestContext(request))
This template contains the template tag link that is suppose to go to service_step1__2.html template
<input type="submit" value="Request Delivery" onclick="change_action('{% url tiptop.views.service_order2 order.pk client.pk 1 %}')"/>

Your order object does not have a pk value, for whatever reason - presumably it's a new unsaved instance. So it's passing an empty string as the first parameter to the URL, and is failing to match your service_order2 url which expects a number in that position.

Related

Error while passing value with url to django view

Error while passing value to view from template using url
Error :
Error during template rendering
In template D:\TONO\DJANGO_TASK\user_auth\templates\auth_app\other-user-listing.html, error at line 114
Reverse for 'add_to_group' with arguments '(name: Administrator,)' not found. 1 pattern(s) tried: ['auth_app\\/<str:username>/']
This my urls.py
url(r'^<str:username>/', views.add_to_group, name="add_to_group"),
This is the call from template
<i class="icon-plus">Add</i>
In your call from template see if you do this if that solves the problem, I remember I was facing this issue and this is what I did:
The syntax for specifying url is {% url namespace:url_name %}. So, check if you have added the app_name in urls.py.
Your url defines a named argument for the url "add_to_group". You should pass this argument as a keyword argument
{% url 'add_to_group' username=username %}
You are mixing the new and old style urls. To use the new style you should use path
path('<str:username>/', views.add_to_group, name="add_to_group"),
Error corrected using :
url(r'^auth_app/add_to_group/(?P<username>[-\w]+)/$', views.add_to_group, name='add_to_group'),

Django How do i determine what arguments are missing?

Trying to access part of code by get request and receiving this error
NoReverseMatch: Reverse for 'homepage' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: [] looked around for help and i think its that am missing some arguments.
here is request am using in my test
req = self.client.get('/password/reset/')
and the code it leads to is as:
class PasswordResetEmailView(FormView):
template_name = 'temp/password_reset.html'
form_class = PasswordResetForm
success_url = 'password_reset_ok'
def get(self, request, *args, **kwargs):
form = self.get_form(self.form_class)
return self.render_to_response(self.get_context_data(form=form))
any guidance ?
You ask specifically about "determining which arguments are missing", but should be irrelevant to your error.
Your error message states that it can't find any URL patterns matching the name "homepage", before attempting any argument matching. Therefore no URLs exist named "homepage" in your setup. If it was an argument mismatch, you'd see a list of named URLs in the error such as "tried X urls."
Either define a URL named home in your URLConf url(r'^home/$', 'home_view', name="homepage") or find the location that is calling reverse('homepage') and remove it. You will find this information in your traceback.

Can't get the url function to work with a specific syntax in django

I've visited the documenation at https://docs.djangoproject.com/en/1.6/ref/templates/builtins/#std:templatetag-url several times and i cant seem to get this syntax to work anywhere:
{% url 'view' obj.id %}
I have a view that takes one parameter so this should work but im only getting NoReverseMatch exception for some strange reason.
When doing it like this:
{% url 'view' obj.id as test %}
test
..im getting the correct url returned back and the link address displays correctly, but when using the above mentioned syntax without setting is as a variable it doesnt work, when i for example use it directly in an element.
When trying to do this which im trying to do:
{% url 'view' obj.id as test %}
<input type="hidden" value="{{ test }}">
im not getting any error but it doesnt seem like im getting any value in the value field because if there were a value in the field the code would do something, and when replacing the variable with a hard-coded string it does work.
When doing this:
{% url 'view' obj.id as test %}
{{ test }}
just to try to print the value it doesnt return anything which i find strange because when using it with the a element in html as shown at the first code line above it displays the correct url.
So basically, im only getting the {% url 'view' obj.id %} syntax to work with the a element of html and only if i define it as a variable.
I would like to use the {% url 'view' obj.id %} syntax in order to have a DRY code. According to the documenation this should work, does anyone have a clue about why this isnt working ? If you need more information then please let me know and i will update the question with the necessary information.
UPDATE:
I'm currently using django 1.6.
The typo in the second snippet has been corrected.
The exact line from urls.py is (im at this page, using the comment system at /comment/ which should do a reverse to the display_story view (it works without problems when hardcoding the value attribute of the input html tag but not with the url function):
url(r'^story/display/(?P<specific_story>\d+)/$', 'base.views.display_story', name='display_story'),
url(r'^comments/', include("django.contrib.comments.urls"))
I have also tried the url function just on the application i have created without going through the comments application but i get the same problem.
This is the error message:
NoReverseMatch at /story/display/1/
Reverse for 'display_story' with arguments '(1,)' and keyword arguments '{}' not found.
Even though i know that the view exists and takes one argument.
This is the html code:
<input type="hidden" name="next" value="{% url 'display_story' story_details.id %}">
I have named views with the name argument and i apply the namespace when necessary.
The django docs says:
exception NoReverseMatch
The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.
but that doesnt seem to be the case.
This urls.py:
url(r'^story/display/(?P<specific_story>\d+)/$', 'base.views.display_story', name='display_story')
should match this view code:
def display_story(request, specific_story):
""" Display details for a specific story. """
story_details = Story.objects.get(id=specific_story)
return render(request, "base/story/display_story.html", {
'story_details': story_details,
})
but for some reason django doesnt think the parameter sent is the the one the function receives when it clearly is stated so in the code.
Update 2:
When giving a keyword argument instead of a positional argument i get this error:
NoReverseMatch at /story/display/1/
Reverse for 'display_story' with arguments '()' and keyword arguments '{u'specific_story': 1}' not found.
This code is used:
{% url 'display_story' specific_story=story_details.id %}
Update 3:
I will update the question with the values of the local vars for the reverse function.
To add some additional infor i ran some code in the python shell:
>>> import base.views
>>> from django.core.urlresolvers import reverse
>>>
>>> test=1
>>> reverse("display_story", kwargs={'test': test})
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/exceed/code/projects/python-2.7/lib/python2.7/site-packages/django/core/urlresolvers.py", line 496, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/Users/exceed/code/projects/python-2.7/lib/python2.7/site-packages/django/core/urlresolvers.py", line 416, in _reverse_with_prefix
"arguments '%s' not found." % (lookup_view_s, args, kwargs))
NoReverseMatch: Reverse for 'display_story' with arguments '()' and keyword arguments '{'test': 1}' not found.
>>>
>>>
>>> reverse("display_story", args=[1])
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/Users/exceed/code/projects/python-2.7/lib/python2.7/site-packages/django/core/urlresolvers.py", line 496, in reverse
return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
File "/Users/exceed/code/projects/python-2.7/lib/python2.7/site-packages/django/core/urlresolvers.py", line 416, in _reverse_with_prefix
"arguments '%s' not found." % (lookup_view_s, args, kwargs))
NoReverseMatch: Reverse for 'display_story' with arguments '(1,)' and keyword arguments '{}' not found.
Unless your view is named 'view' in the urlconf, you should use the full python dotted import path in the tag. For example:
{% url 'my_app.views.my_view' obj.id %}
If you want to test it properly, you can also use the django shell
python manage.py shell
and try the 'reverse' function:
from django.core.urlresolvers import reverse
reverse('my_app.views.my_view' args=[1])
>> '/my/awesome/url/1'
edit: also make sure that you didn't namespace your urls, if you did, you should include the namespace in the url tag:
{% url 'namespace:view' obj.id %}
another edit, because I have a feeling this might be it. I apologise for abusing the answer system instead of comments, but since I'm only starting out my reputation is too low.
Can you post the full urlconfig from your root urls.py up until the 'misbehaving' url? I have had cases where an url captured a group (say, an ID) and then included a bunch of other urls, leading to two required arguments for the reverse function.

Django HTTPResponseRedirect & Reverse with optional parameter

How do I use Django's Reverse with an optional parameter for info? I keep on getting
views.py:
def cartForm(request, prod):
if request.method=="POST":
quantity = request.POST.get('quantity', False)
if quantity:
add_to_cart(request, prod, quantity)
return HttpResponseRedirect(reverse("cart"))
#if no quantity indicated, display error message
return HttpResponseRedirect(reverse('products.views.info', kwargs={'prod': prod, 'error':True}))
def info(request, prod, error=False):
prod = Product.objects.get(id=prod)
return render(request, "products/info.html", dict(product = prod, error=error))
urls.py:
url(r'^(?P<prod>\d+)/', "products.views.info", name='info'),
I keep on getting the following error:
Reverse for 'products.views.info' with arguments '()' and keyword arguments '{'prod': u'2', 'error': True}' not found. 1 pattern(s) tried: ['products/(?P<prod>\\d+)/']
You can pass optional GET parameters as:
reverse('products.views.info', kwargs={'prod': prod})+'?error=true&some_other_var=abc'
reverse returns the resolved URL as string, so you can concatenate as many GET parameters as you want.
Not a direct answer but : why don't you just use the Messages framework (https://docs.djangoproject.com/en/1.6/ref/contrib/messages/).
Try with optional group in url:
# change (?P<error>\d+) to (?P<error>[a-zA-Z]+) to catch strings in error value
url(r'^(?P<prod>\d+)(?:/(?P<error>\d+))?/', "products.views.info", name='info'),
source: Making a Regex Django URL Token Optional
Adding an argument to the view function doesn't not make it into a URL pattern, in your case you have added the argument directy to the view method, but not mapped it to the URL.
Therefore, when you try to reverse the URL, a pattern that has error is not found, which is why you are getting the error.
You have two options:
Make the pattern optional which I do not recommend.
Map the same view to multiple URLs, with the optional one first as the patterns are matched in the order found:
url(r'^(?P<prod>\d+)/(?P<error>\d+)/', "products.views.info", name='info-error'),
url(r'^(?P<prod>\d+)/', "products.views.info", name='info'),
Now, in your view:
from django.shortcuts import redirect
def cartForm(request, prod):
if request.method=="POST":
quantity = request.POST.get('quantity', False)
if quantity:
add_to_cart(request, prod, quantity)
return HttpResponseRedirect(reverse("cart"))
#if no quantity indicated, display error message
return redirect('info-error', prod=foo, error=True)
Here I am using the redirect shortcut

Django url template returns NoReverseMatch

continuing question from here. after fixing the template according to #dannyroa - removing the quotes from the template name I still get NoReverseMatch error:
NoReverseMatch at /transfers/41/
Reverse for 'description_url' with arguments '(u'\u05ea\u05e7\u05e6\u05d9\u05d1 \u05d4\u05e9\u05db\u05e8 - \u05d1\u05d9\u05ea \u05d4\u05e0\u05e9\u05d9\u05d0',)' and keyword arguments '{}' not found.
Request Method: GET
Request URL: http://127.0.0.1:8000/transfers/41/
Django Version: 1.4
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'description_url' with arguments '(u'\u05ea\u05e7\u05e6\u05d9\u05d1 \u05d4\u05e9\u05db\u05e8 - \u05d1\u05d9\u05ea \u05d4\u05e0\u05e9\u05d9\u05d0',)' and keyword arguments '{}' not found.
the template now:
<a href='{% url description_url transfer.description %}'>{{transfer.description}}</a>
the urlconf:
url(r'^description/(?P<description>[\w ]+)/$',
'transfers.views.description_ListView',
name = 'description_url')
the view:
def description_ListView(requesst,**kwargs):
template_name = 'transfers/description.html'
o = get_list_or_404(Transfer, description =kwargs['description'])
#print ('o:',o)
context_object_name = "transfer_name_list"
return render_to_response(template_name,{context_object_name:o,'description':kwargs['description']})
this problem is really starting to get me down. I know I can write a specific method on the Transfer Model (maybe with #permalink) returning the right url for each view. but this is a lot of work and certainly frustrating to do this only because of my miserable failure at using the {%url %} template tag
thanks for the help

Categories