I need to support following urls in single url regex.
/hotel_lists/view/
/photo_lists/view/
/review_lists/view/
how to support all above urls in single views?
I tried something like below
url(r'^\_lists$/(?P<resource>.*)/$', 'admin.views.customlist_handler'),
edit:
hotel,photo, review is just example. that first part will be dynamic. first part can be anything.
If you wish to capture the resource type in the view, you could do this:
url(r'^(?P<resource>hotel|photo|review)_lists/view/$', 'admin.views.customlist_handler'),
Or to make it more generic,
url(r'^(?P<resource>[a-z]+)_lists/view/$', 'admin.views.customlist_handler'), #Or whatever regex pattern is more appropriate
and in the view
def customlist_handler(request, resource):
#You have access to the resource type specified in the URL.
...
You can read more on named URL pattern groups here
Related
This is my current url path is as http://localhost:8000/api/projects/abcml/2021
and in the urls.py page I am passing as path("api/projects/<str:project_handle>/<int:year>", functionname...) and in the view, I accept this parameters with self.kwargs.get method.
I want to pass url as this format http://localhost:8000/api/projects/abcml/?year=2021
What changes do I need to make in url pattern?
I tried this path("api/projects/<str:project_handle>/?year=<int:year> but did not seem correct also in the view page, instead of self.kwargs.get I changed it to self.request.query_params.get for year parameter. That did not work either. Error it throwing is Page not found (404).
The query string [wiki] is not part of the path, and therefore can not be matched.
You thus specify as path:
path('api/projects/<str:project_handle>/', functionname)
In the view, you can access the data with self.request.GET['year'] and this will return a string or a KeyError in cas the year was not provided in the query string.
I am working on a django project which have a posts page. I have its url as follows:
path('posts/<str:sort>', views.posts, name='posts'),
and this is what its view looks like:
def posts(request,sort)
b=""
if b=="time":
posts=Post.objects.all().order_by(b)
else:
posts=Post.objects.all()
return render(request,posts.html,{'posts':posts})
Now what I want is that if there is nothing passed as sort in the url or the url is like : /posts/ I want to display all posts but if the parameter is 'time' then I want to order_by as in my view. But currently if nothing is passed in url for sort then I get the error that no path found the url.
str converter is defined as follows:
class StringConverter:
regex = '[^/]+'
# other methods
Which means it requires at least one character (note +, not *). You can create a new url mapping and manually pass empty string as sort parameter:
path('posts/', views.posts, kwargs={'sort': ''})
You can also register your own converter to allow empty string or just switch to plain old re_path. These options are preferred in case if you want to reduce code repetition and reuse this behavior somewhere else. They also allow you to keep the same url name (useful if you're planning to reverse urls)
Is there a way for Flask to accept a full URL as a URL parameter?
I am aware that <path:something> accepts paths with slashes. However I need to accept everything including a query string after ?, and path doesn't capture that.
http://example.com/someurl.com?andother?yetanother
I want to capture someurl.com?andother?yetanother. I don't know ahead of time what query args, if any, will be supplied. I'd like to avoid having to rebuild the query string from request.args.
the path pattern will let you capture more complicated route patterns like URLs:
#app.route('/catch/<path:foo>')
def catch(foo):
print(foo)
return foo
The data past the ? indicate it's a query parameter, so they won't be included in that patter. You can either access that part form request.query_string or build it back up from the request.args as mentioned in the comments.
Due to the way routing works, you will not be able to capture the query string as part of the path. Use <path:path> in the rule to capture arbitrary paths. Then access request.url to get the full URL that was accessed, including the query string. request.url always includes a ? even if there was no query string. It's valid, but you can strip that off if you don't want it.
#app.route("/<path:path>")
def index(path=None):
return request.url.rstrip("?")
For example, accessing http://127.0.0.1:5000/hello?world would return http://127.0.0.1:5000/hello?world.
I have the following URL:
http://127.0.0.1:8000/databaseadd/q=DQ-TDOXRTA?recipe=&recipe=&recipe=&recipe=&recipe=
I'd like to match if the keyword "recipe=" is found in the url.
I have the following line in django url.py but it's not working:
url(r'recipe=', 'plots.views.add_recipe'),
Are the "&" and the "?" throwing it off?
Thanks!
Alex
Part after the ? not used in the url dispatching process because it contains GET parameters. Otherwise you will not be able to use a GET request with parameters on patterns like r'^foo/&' (ampersand at the end means the end of the string, and without it it would be harder to use patterns like r'^foo/' and r'^foo/bar/' at the same time).
So for your url the pattern should look like r'^databaseadd/q=DQ-TDOXRTA&' and then in add_recipe view you need to check for the recipe GET parameter.
I'd like to match if the keyword "recipe=" is found in the url
You could try something like :
import re;
re.match (r'.*recipe=.*', "http://127.0.0.1:8000/databaseadd/q=DQ-TDOXRTA?recipe=&recipe=&recipe=&recipe=&recipe=")
Need a little help with my urls.py and other stuff.
How can I replicate this in Django?
1) When user requests a non-existent page it will redirect to one up the directory level. Ex: example.com/somegoodpage/somebadpage should be redirected to example.com/somegoodpage.
2) When user requests page example.com/foo/bar/?name=John it will make url to example.com/foo/bar/name=John
3) When user requests page example.com/foo/bar/John it will change url to example.com/foo/bar/name=John.
Any help is greatly appreciated. Thank You.
For 1), if you don't want to do a separate route for every single route on your website, you'll need middleware that implements process_exception and outputs an HttpResponseRedirect.
For 2 and 3, those are rules that are presumably limited to specific routes, so you can do them without middleware.
2 might be doable in urls.py with a RedirectView, but since the relevant bit is a query string argument, I would probably make that an actual view function that looks at the query string. Putting a ? character in a url regex seems strange because it will interfere with any other use of query strings on that endpoint, among other reasons.
For 3, that's a straightforward RedirectView and you can do it entirely in urls.py.
according to django doc for number 1:
django URL dispatcher runs through each URL pattern, in order, and stops at the first one that matches the requested URL, so add a pattern that matches "somebadpage"s and assign it to a view which redirects the user to "somegoodpage".
for number 2:
the doc says "The URLconf searches against the requested URL, as a normal Python string. This does not include GET or POST parameters, or the domain name."
so i don't think that you can get the "?name=John" in url dispather, so if you describe what you want to do maybe I can help better
and for 3:
to capture bits of the URL and pass them as positional arguments to a view you should use named regular-expression groups, for example :
url(r'^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$', 'news.views.month_archive'),
and the request to /articles/2005/03/ would call the function news.views.month_archive(request, year='2005', month='03'), instead of news.views.month_archive(request, '2005', '03').
hope this helped :)