Error NoReverseMatch on Reverse Django URL - django

I have declared an url like following in django 1.7:
url(r'^page(/\w{2}/|/)$', MyView.as_view(), name='my_name'),
In my template, I want to reverse the url from its name. I tried:
<form method="post" action="{% url 'my_namespace:my_name' variable %}">
<form method="post" action="{% url 'my_namespace:my_name' %}">
But nothing works, it throwed exception:
Reverse for 'my_name' with arguments '(u'test',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['page(\/\w{2}\/|\/)$']
Please help by giving me some advice. Thank you.

The regex appears incorrect for matching the argument 'test'.
If we take a look at the regex (/\w{2}/|/),
It appears to be capturing two groups which are separated by an 'OR' (|) operator.
The first group is /\w{2}/. This is only going to match '/' followed by \w only 2 times followed by '/'.
The second group is only matching '/'.
'test' doesn't match either one of these cases so it raises an exception.
I believe the correct regex we are looking to capture here would be,
(\w+)
The correct URL structure would look like this,
url(r'^page/(\w+)/$', MyView.as_view(), name='my_name')
url(r'^page/$', MyView.as_view(), name='my_name')
This would match given the argument 'test' because the regex (\w+) says match any of the characters in this group [a-zA-Z0-9_] one or more times and each character in 'test' falls into this category.

Related

How to query by string

In Product model and i want to query by food title. and return me NoReverseMatch error
html url:
some text
views.py:
def product(request, food_name):
product = Catalog.objects.get(food_name=food_name)
return render(request, 'food/product.html', {'product':product})
url.py
url(r'^product/(?P<food_name>\w+)/', food_views.product, name='product'),
Trace
NoReverseMatch: Reverse for 'product' with arguments '()' and keyword arguments '{u'food_name': u'%D9%86%D8%A7%D9%86%20%D8%A8%D9%88%D8%B1%DA%A9'}' not found. 1 pattern(s) tried: [u'product/(?P<food_name>\\w+)/']
Remove the urlencode, you don't need it
some text
urlencode is used when you need to encode a string in a way that will allow it to be used inside a url (such as when you're adding get parameters). Above, you are just passing a string parameter to a function that is constructing a url.
You seem to be trying to encode arabic characters into your url which are not matched by \w so you need to update your url to support these
^product/(?P<food_name>[\w\u0600-\u06FF]+)/
Will handle most of these (See this regexr example), but I'm not familiar with arabic enough to know what the unicode for ک is
I believe it's because \w+ doesn't match URL-encoded string. Try to change it temporarily to .* (just to check if there are not any other issues). If it will work — change \w+ to better template matching URL-encoded strings.

Only one letter of string is being passed to Django views function from template

HTML form:
<form id="save_form" method="post" action="{% url 'project_save' usernames=username project_name='lion' %}">
Notice the arg 'project_name's value is 'lion'
views.py:
def projectz_save(request, usernames, project_name):
template = loader.get_template('project_view/index.html')
context = RequestContext(request, {"username": usernames, "project": project_name})
return HttpResponse(template.render(context))
urls.py:
urlpatterns = patterns('',
url(r'^$', views.index, name='index'),
url(r'^(?P<usernames>\w+)(?P<project_name>\w+)save$', views.projectz_save, name='project_save'),
)
What happens is that only the 'n' in 'lion' is being passed as an argument. When I re-render the page, the template variable "project" now has the value 'n' instead of 'lion.' Any idea why this is happening?
It happens if I use a variable instead of a string (which is obviously the ultimate goal), but even simplified down to a simple string it's still happening.
Your problem is that while the template is correctly constructing the URL, your urls.py regexp is too greedy.
Specifically, you have no divider between your usernames named group and your project name named group:
r'^(?P<usernames>\w+)(?P<project_name>\w+)save$'
Given any sequence of word characters, all but the last will be matched by the \w+ in the usernames group. The last will be matched by the project_name group, because + requires at least one character. So if username in the template is 'johndoe', the url tag will construct the URL:
johndoelionsave
The regexp will then match johndoelio as the usernames group, since all of those are matched by \w+, n as the project_name group, since it's matched by \w+, and then the fixed save and end-of-string parts.
Your best fix will be to break up the URL pattern so that the parsing is unambiguous. I suggest:
r'^(?P<usernames>\w+)/(?P<project_name>\w+)/save$'
In which case the template tag will produce:
johndoe/lion/save
and the regexp will parse out the details you want.

Regular Expression Exact Keyword Exclusion

Hi guys I am looking for a regular expression which will not match any given string that is exactly equal to a few keywords I will determine manually.
The purpose is to edit my urlrewrite.xml which can accept regexps in following format
<rule>
<from>^/location/([A-Z]+)/name/([A-Z]+)</from>
<to>/login?name=$2&location=$1</to>
</rule>
For example I want to redirect everything after / which is not 'login' and 'signup' to another page. I am trying following ones but none satisfies my request.
^/(?!(login|signup).*
^/(?!(login|signup)[A-Za-z0-9]+
Because I want it to match only if input is exactly 'login' or 'signup' however, it declines 'loginblabla', too.
Any solutions are highly appreciated. :)
You need to add a $ anchor at the end of the lookahead:
^/(?!(login|signup)$)(.+)
Now anything that isn't exactly login or signup will be captured in group $1.

Uncommon django urlpattern

Suppose I've got urls on my site which look like /qwe/asd/zxc/wer/sdf/xcv/ (unknown number of \w+ blocks separated by slashes).
Is that possible? to construct a urlpattern to catch those urls so that:
a view function would get all those \w+ strings in *args list to it
the {% url qwe asd zxc wer sdf xcv %} templatetag would reconstruct supposed /qwe/asd/zxc/wer/sdf/xcv/ url the right way
Thanks
For No.1 (r'^(?P<url>[\w/]+)$', 'views.handler') could do that.

NoReverseMatch error in django app

I am receiving this error in one of my templates and cant seem to figure out what's wrong.
`NoReverseMatch: Reverse for 'getimagefile'
with arguments '(12L, 'afN9LRzESh4I9CGe6tFVoA==\n')' and
keyword arguments '{}' not found.
My urls.py contains:
urlpatterns = patterns('myproj.myapp.views',
url(r'^getimage/(?P<extractedcontent_id>\d+)/(?P<encpw>.*)/$','getimagecontent',name='getimagefile'),
)
My views.py contains:
def getimagecontent(request,extractedcontent_id,encpw):
........
And finally my template that's giving me the error contains the following line:
<li class="active"><img src="{% url getimagefile img,encpw %}" title=""/></li>
Your encpw variable ends in a newline character, by default the . regular expression character does not capture these. Try altering your regex so the DOTALL flag is turned on, which will match for newline characters.
url(r'(?s)^getimage/(?P<extractedcontent_id>\d+)/(?P<encpw>.*)/$','getimagecontent',name='getimagefile'),
Notice the (?s) at the very beginning this will turn the DOTALL flag on.
You don't show where encpw comes from, but it appears to have a newline character (\n) at the end, which won't match the url regex.