So I have this URL scheme:
(r'^test/(?P<name>\d+)/', 'test'),
def test(request, name):
html = "it worked"
return HttpResponse(html)
however, when I go to the following URL, I get a 404 error:
http://127.0.0.1:8000/test/words/
What am I doing wrong?
You probably meant to use \w instead, e.g.:
(r'^test/(?P<name>\w+)/', 'test'),
\d matches only digits; \w matches any alphanumeric character.
Python Regular Expression HOWTO by A.M. Kuchling.
Related
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.
I have an url like below and wanted to use RegEx to extract segments like: Id:Reference, Title:dfgdfg, Status.Title:Current Status, CreationDate:Logged...
This is the closest pattern I got [=,][^,]*:[^,]*[,&] but obviously the result is not as expected, any better ideas?
P.S. I'm using [^,] to matach any characters except , because , will not exist the segment.
This is the site using for regex pattern matching.
http://regexpal.com/
The URL:
http://localhost/site/=powerManagement.power&query=_Allpowers&attributes=Id:Reference,Title:dfgdfg,Status.Title:Current Status,CreationDate:Logged,RaiseUser.Title:标题,_MinutesToBreach&sort_by=CreationDate"
Thanks,
You haven't specified what programming language you use. But almost all with support this:
([\p{L}\.]+):([\p{L}\.]+)
\p{L} matches a Unicode character in any language, provided that your regex engine support Unicode. RegEx 101.
You can extract the matches via capturing groups if you want.
In python:
import re
matchobj = re.match("^.*Id:(.*?),Title:(.*?),.*$", url, )
Id = matchobj.group(1)
Title = matchobj.group(2)
I am trying to pass an ID of a table to my function but I am not sure what's going on.
if I hard code the ID number does work, if I use the (?Pd+) with d+ so it use as many digits, like in the tutorials. doesn't work. should this be different?
thanks guys.
my urls
from django.conf.urls import patterns, include, url
from polls import views
urlpatterns = patterns('',
#url(r'^main_site/$', views.main_site),
url(r'^vote/$', views.vote),
url(r'^stadistics/$', views.stadistics),
# using it like this doesn't work
url(r'^vote/Restaurant_Info/(?P<rest_id>d+)/$', views.restaurant_menu),
#testing the info of the restaurant
# hard coding the id of the restaurant does work
url(r'^vote/Restaurant_Info/4/$', views.restaurant_menu),
my view
def restaurant_menu(request, rest_id="0"):
response = HttpResponse()
try:
p = Restaurant.objects.get(id=rest_id)
response.write("<html><body>")
response.write("<p>name of the restaurant</p>")
response.write(p.name)
response.write("</body></html>")
except Restaurant.DoesNotExist:
response.write("restaurant not found")
return response
You're missing a backslash in your expression, currently d+ matches the character d literally "one or more" times. The backslash in combination with a literal character creates a regular expression token with special meaning.
Therefore, \d+ will match digits 0 to 9 "one or more" times.
url(r'^vote/Restaurant_Info/(?P<rest_id>\d+)/$', views.restaurant_menu)
You're missing a slash. It should be (?P<rest_id>\d+)
url(r"^vote/Restaurant_Info/(?P<rest_id>\d+)/$", views.restaurant_menu),
I am using TinyMCE in my Django Admin site. I need to validate that no disallowed HTML Tags get submitted. This is what I tried:
1) Validation Method
def check_for_invalid_html_tags(value) :
compiled_regex = re.compile('<(?!/?(p|div|ul|li)(>|\s))[^<]+?>')
if compiled_regex.match(value):
raise ValidationError('Invalid Tags')
2) Validation Rule
content = tinymce_models.HTMLField(validators=[check_for_invalid_html_tags])
This does not seem to work, as any submission is let through as valid. When I change the tinymce_models.HTMLField to models.TextField, the rule works perfectly. Thus I believe that the issue is as a result of TinyMCE.
Can anybody help?
I read the doc and there is a slight difference between match and search
match:
If zero or more characters at the beginning of string ...
search:
Scan through string looking for the first location ...
search() vs. match()
since what your are looking for might be everywhere in your string you need to use search instead of match. An other point, you might neeed to set the fag re.S or re.DOTALL since you might have newline in your input.
Make the '.' special character match any character at all, including a newline; without this flag, '.' will match anything except a newline.
So here is the check_for_invalid_html_tags in a functor and a working solution.
import re
class CheckForInvalidHtmlTags(object):
compiled_regex = re.compile('<(?!/?(p|div|ul|li)(>|\s))[^<]+?>')
def __call__(self, value):
if self.compiled_regex.search(value):
print 'error'
else:
print 'ok'
c = CheckForInvalidHtmlTags()
c('test test <a>test<a> test') # print error
c('test <p> test</p>') # print ok
c('test<a> test</a><p>test</p>test') # print error
Your validation method must actually be a validator, which has special methods like __call__. Use one of django's core validators, like the regex validator.
from django.core.validators import RegexValidator
check_for_invalid_html_tags = RegexValidator(
regex=''<(?!/?(p|div|ul|li)(>|\s))[^<]+?>'',
message='Invalid Tags',
code='invalid_content'
)
Then in your model:
content = tinymce_models.HTMLField(validators=[check_for_invalid_html_tags])
I have urls where spaces are replaced with the "-" character.
So I made a url regex like this:
url(r'^(?P<item_url>(\w+-?)*)/$', 'detail'),
my view:
def detail(request, item_url):
i = get_object_or_404(Page, url=item_url,published=True)
return render_to_response('item/detail.html', {'item':i},
context_instance=RequestContext(request))
Unfortunately this keeps django extremely busy on urls with more than 20 characters. The process hangs for 20sec - 1 minute and then returns the correct result. Is this based on a wrong regex I'm using?
Try the following url pattern:
url(r'^(?P<item_url>[\w-]+)/$', 'detail'),
[\w-]+ will match one or more alphanumeric characters or hyphens.