Making a Regex Django URL Token Optional - regex

You have a URL which accepts a first_name and last_name in Django:
('^(?P<first_name>[a-zA-Z]+)/(?P<last_name>[a-zA-Z]+)/$','some_method'),
How would you include the OPTIONAL URL token of title, without creating any new lines. What I mean by this is, in an ideal scenario:
#A regex constant
OP_REGEX = r'THIS IS OPTIONAL<title>[a-z]'
#Ideal URL
('^(?P<first_name>[a-zA-Z]+)/(?P<last_name>[a-zA-Z]+)/OP_REGEX/$','some_method'),
Is this possible without creating a new line i.e.
('^(?P<first_name>[a-zA-Z]+)/(?P<last_name>[a-zA-Z]+)/(?P<title>[a-zA-Z]+)/$','some_method'),

('^(?P<first_name>[a-zA-Z]+)/(?P<last_name>[a-zA-Z]+)(?:/(?P<title>[a-zA-Z]+))?/$','some_method'),
Don't forget to give title a default value in the view.

In case your are looking for multiple optional arguments, without any required ones, just omit "/" at the beginning, such as:
re_path(r'^view(?:/(?P<dummy1>[a-zA-Z]+))?(?:/(?P<dummy2>[a-zA-Z]+))?(?:/(?P<dummy3>[a-zA-Z]+))?/$', views.MyView.as_view(), name='myname'),
which you can browse at:
http://localhost:8000/view/?dummy1=value1&dummy2=value2&dummy3=value3

Related

Django Rest API Url Pattern to handle . (dot) symbol

Creating Django REST API, Need suggestions to handle the .(dot char) in the urlpatterns. Below is the example detail:
I have a Model (test) with name as one of the fields and name value is of format ABC.XYZ
Below URL pattern does not work when name = ABC.XYZ
url(r'^tests/(?P<string>[\w\-]+)/$', views.tests.as_view(), name='api_tests_name')
You can add the dot to the character group in the regex:
url(r'^tests/(?P<string>[\w\-.]+)/$', views.tests.as_view(), name='api_tests_name')
So now you make a request with tests/foo.bar/ as path for example.

How to use variable at start of django url to return to view?

I am trying to pass the first part of a django url to a view, so I can filter my results by the term in the url.
Looking at the documentation, it seems quite straightforward.
However, I have the following urls.py
url('<colcat>/collection/(?P<name>[\w\-]+)$', views.collection_detail, name='collection_detail'),
url('<colcat>/', views.collection_view, name='collection_view'),
In this case, I want to be able to go to /living and have living be passed to my view so that I can use it to filter by.
When trying this however, no matter what url I put it isn't being matched, and I get an error saying the address I put in could not be matched to any urls.
What am I missing?
<colcat> is not a valid regex. You need to use the same format as you have for name.
url('(?P<colcat>[\w\-]+)/collection/(?P<name>[\w\-]+)$', views.collection_detail, name='collection_detail'),
url('(?P<colcat>[\w\-]+)/$', views.collection_view, name='collection_view'),
Alternatively, use the new path form which will be much simpler:
path('<str:colcat>/collection/<str:name>', views.collection_detail, name='collection_detail'),
path('<str:colcat>/', views.collection_view, name='collection_view'),

What would be Djnago's url pattern to match and fetch out a url (coming appended to site's domain as a GET request)?

Suppose my site's domain is mysite.com , now whenever a request comes in this form : mysite.com/https://stackoverflow.com :I want to fetch out this url "https://stackoverflow.com" and send it to the corresponding view.
I have tried this pattern :
url(r'^(?P<preurl>http[s]?://(?:[a-zA-Z]|[0-9]|[$-_#.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+)$',prepend_view)
regex of which matches the incoming appended url and assigns variable preurl the value "https://stackoverflow.com", which I access in corresponding view function .
This works fine for above example but my url pattern is failing in case of some exceptional urls..
Please suggest a robust url pattern by taking into consideration all exceptional urls too, like the following:
ftp://ftp.is.co.za/rfc/rfc1808.txt
http://www.ietf.org/rfc/rfc2396.txt
ldap://[2001:db8::7]/c=GB?objectClass?one
mailto:John.Doe#example.com
news:comp.infosystems.www.servers.unix
tel:+1-816-555-1212
telnet://192.0.2.16:80/
urn:oasis:names:specification:docbook:dtd:xml:4.1.2
That is, if a request comes like :
mysite.com/ldap://[2001:db8::7]/c=GB?objectClass?one
I should be able to get the value "ldap://[2001:db8::7]/c=GB?objectClass?one" in variable preurl
You don't have to make this type of complex url pattern, First, make a URL pattern that matches everything.
url(r'^.*/$', views.fast_track_service, name='fast_track'),
and append it to the end in urlpatterns in your urls.py then in your view, Use request object, So You can get the full path of get request with this method,
fast_track_url = request.get_full_path()[1:]
and then once you got the url try validating that with URLValidator like this.
if not 'http://' in fast_track_url and not 'https://' in fast_track_url:
fast_track_url = 'http://' + fast_track_url
url_validate = URLValidator()
try:
url_validate(fast_track_url)
except:
raise Http404
If you want to validate other complicated URL like mailto etc, then you can write your own validator.

how to prevent the extra slashes comin in the url of the browser

urls.py
url(r'^kebreading/$', 'KEBReading1',name="kebreading"),
url(r'^kebreading/(?P<param>\w*)/(?P<date>\w*)/(?P<year>\w*)/(?P<month>\w*)/$', kEBReading1',name="kebreading")
i have a view which i pass 5 parameters to it. and the same view is being called when i dont pass any parameter. but five slashes gets appended to the url in the browser even wen i don pass any parameters. how to prevent this happening???
You can use the regexp ? sign to create an optional group and use ?: so Django do not pass this group as an *arg parameter
Something like :
url(r'^kebreading/(?:(?P<param>\w*)/(?P<date>\w*)/(?P<year>\w*)/(?P<month>\w*)/)?$', kEBReading1',name="kebreading")
There is a similar question #2325433

Django: How can I make a part of the URL optional

I have a url in which I would like to make the status token optional. If the status token is not provided in the url I give a default value in the view method argument. I tried replacing the token with this (?:/(?P<status>\d+))?$ but doesn't seems to work well. Thanks
url(r'^(?P<status>\d+)/$', frequest_list, name="frequest_list"),
def request_list(request, status=1):
...
...
Update:
This was the pattern I was trying:
url(r'^(?:/(?P<status>\d+))?$', frequest_list, name="frequest_list"),
So, if I try localhost/features/ works well
But if I do localhost/features/1/ it fails
Just create a second url entry that calls the same view:
url(r'^features/$', frequest_list, name="frequest_list_default"),
url(r'^features/(?P<status>\d+)/$', frequest_list, name="frequest_list"),
I use single url optional captures in some of my projects, and they work fine. You might want to adjust your pattern to make the trailing / optional. I think that is what is causing your url to not match. Django does have an "APPEND_SLASH" settings bool that will add that on to your urls if they are missing it and don't match:
url(r'^features(?:/(?P<status>\d+))?/?$', frequest_list, name="frequest_list")
The optional / could probably also be written like this:
url(r'^features/?(?:(?P<status>\d+)/?)?$', frequest_list, name="frequest_list")