I'm having a bit of trouble configuring the following url. I want it to be able to match a pages which start off with a category and then finish with a slug, examples:
/category1/post1/
/category2/post2/
/category3/post3/
/category1/post4/
/category2/post5/
I've tried many different methods with no success... I always get an "is not a valid regular expression" error.
This is how I thought it should work:
url(r'^(?P<category1|category2|category3>[\w\-]+)/(?P<slug>[\w\-]+)/$', blog_post, name = 'blog_post'),
I am fairly new to regex and trying to learn so any help on this one with an explanation would be much appreciated :)
Your pattern is incorrect; you are putting the alternative values in the wrong place. You put them in the name of the group:
(?P<category1|category2|category3>...)
Put them in the part the name is supposed to match instead:
(?P<category>category1|category2|category3)
Making the full registration:
url(r'^(?P<category>category1|category2|category3)/(?P<slug>[\w\-]+)/$', blog_post, name='blog_post'),
I'm assuming your blog_post callable looks something like:
def blog_post(category, slug):
Related
I'm using Django Full Text search to search across multiple fields but have an issue when searching using partial strings.
Lets say we have a report object with the name 'Sample Report'.
vector = SearchVector('name') + SearchVector('author__username')
search = SearchQuery('Sa')
Report.objects.exclude(visible=False).annotate(search=vector).filter(search=search)
The following QuerySet is empty but if I include the full word 'Sample' then the report will appear in the QuerySet.
Is there anyway to use icontains or prefixing with django full text search?
This is working on Django 1.11:
tools = Tool.objects.annotate(
search=SearchVector('name', 'description', 'expert__user__username'),
).filter(search__icontains=form.cleaned_data['query_string'])
Note the icontains in the filter.
#santiagopim solution is correct but to address Matt's comment for if you get the following error:
ERROR: function replace(tsquery, unknown, unknown) does not exist
at character 1603 HINT: No function matches the given name
and argument types. You might need to add explicit type casts.
You have to remove the call to SearchQuery and just use a plain string.
I know this doesn't address the underlying issue for if you need to use SearchQuery but if you are like me and just need a quick fix, you can try the following.
vector = SearchVector('name') + SearchVector('author__username')
# NOTE: I commented out the line below
# search = SearchQuery('Sa')
search = 'Sa'
Report.objects.exclude(visible=False).annotate(search=vector)\
.filter(search__icontains =search)
This other answer might be helpful.
I currently have a django view with a fairly simple search function (takes user input, returns a list of objects). For usability, I'd like the option of passing search paramters via url like so:
www.example.com/search/mysearchstring
Where mysearchstring is the input to the search function. I'm using regex to validate any alphanumeric or underscore characters.
The problem I'm having is that while this works perfectly in my development environment, it breaks on the live machine.
Currently, I am using this exact same method (with different regex patterns) in other django views without any issues. This leads me to believe that either.
1) My regex is truly bad (more likely)
2) There is a difference in regex validators between environments (less likely)
The machine running this is using django 1.6 and python 2.7, which are slightly behind my development machine, but not significantly.
urls.py
SEARCH_REGEX = '(?P<pdom>\w*)?'
urlpatterns = patterns('',
....
url(r'^polls/search/' + SEARCH_REGEX, 'polls.views.search'),
...)
Which are passed to the view like this
views. py
def search(request, pdom):
...
When loading up the page, I get the following error:
ImproperlyConfigured: "^polls/search/(?P<pdom>\w*)?" is not a valid regular expression: nothing to repeat
I've been scratching my head over this one for a while. I've attempted to use a few different methods of encapsulation around the expression with no change in results. Would appreciate any insight!
I would change it to this:
SEARCH_REGEX = r'(?P<pdom>.+)$'
It's usually a good idea to use raw strings r'' for regular expressions in python.
The group will match the entire content of the search part of your url. I would handle query string validation in the view, instead of in the url regex. If someone tries to search polls/search/two+words, you should not return a 404, but instead a 400 status and a error message explaining that the search string was malformed.
Finally, you might want to follow the common convention for search urls. Which is to use a query parameter called q. So your url-pattern would be ^polls/search/$, and then you just handle the q in the view using something like this:
def search_page_view(request):
query_string = request.GET.get('q', '')
I'm testing MongoAlchemy for a project and I've to search user by name.
I'm trying to make a regex but query result is always empty.
I tried two methods :
import re
users = User.query.filter({"name":re.compile("/a/", re.IGNORECASE)}).all()
And :
users = User.query.filter(User.name.regex('/a/', ignore_case=True)).all()
Even if I use a very general regex like /.*/, the result is always empty.
Thank you.
In python regular expressions are not defined using /regexp/, this is javascript syntax.
The proper way to initialize regular expressions would be:
re.compile(r".*", re.IGNORECASE)
So you should use:
users = User.query.filter({"name": re.compile(r".*", re.IGNORECASE)}).all()
My problem is people keep linking to example.com/FooBar but the actual link is example.com/foobar.
My current regex is...
SLUG = '(?P<slug>[\w\d-]+)'
I hope that makes sense. I was surprised I couldn't find this question already asked. Maybe my google fu is weak today.
The regex matches both. The difficulty is that you've likely got a query like:
obj = MyModel.objects.get(slug=slug)
Which isn't matching.
To fix this, change the query to:
obj = MyModel.objects.get(slug=slug.lower())
Also your query could be like
obj = MyModel.objects.get(slug__icontains=slug)
The icontains field lookup will do a case insensitive match
I was going through the django tutorial and though now almost everything there seems pretty clear, I am having trouble understanding the regex while matching the urls :
r'^(?P<poll_id>\d+)/$
what does (?P<poll_id>\d+) do ?
I am understanding that after stripping off the "34/" from "polls/34/", The polls.url is being called and there the keyword urlpatterns is being looked for , but how does poll_id get this value 34 ?
I know only a bit of regex, so thats why it might be hard for me to read.
Also, here is the reference that I am using for this question :Tutorial Part3
It's a regex that takes the poll_id (a number) as a variable.
The corresponding view is:
def detail(request, poll_id):
return HttpResponse("You're looking at poll %s." % poll_id)
Now when you go to example.com/polls/34/, it knows you are looking for poll number 34, and it brings that in to the view as the poll_id.
So in your view, poll_id = 34. This allows you to display or manipulate this specific poll.
Essentially the point of the regex in this case is to allow you to view a large number of specific polls without having to create an explicit url for each one.
To clarify, this regex is saying take any number \d+, save it as poll_id, and proceed to this view with that poll_id.
To support for Dan Hoerst 's answer: yup, django uses regular expression to extract the poll_id for the view. The underneath of this is:
import re
r = re.compile(r'^poll/(?P<poll_id>\d+)/$')
r.match('poll/132/').groups() # ('132',)