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

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")

Related

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.

URL not resolving correctly in Django URL

I just tried the following in my AJAX update:
[Server]/secTypes/Update
This maps to the following url in URLS.py:
url(r'^secTypes/Update/', equity.views.updateSecTypes, name='updateSecTypes'),
This doesn't resolve to the following function in my view.
But when I change the URL expression to:
url(r'^su/', equity.views.updateSecTypes, name='updateSecTypes')
It works fine.
What in the URL resolver is not getting accurately mapped? Is it the forward slash?
I think it has to do with something related to the regex so if someone understands this better can help me that would be appreciated.
From the url patterns in your comments, it looks like you had another matching pattern before the one in your question.
There are two simple solution for this.
Move that first pattern down. Change this:
url(r'^secTypes/', equity.views.getSecTypes, name='getSecTypes'),
url(r'^secTypesAll/', equity.views.getSecTypesAll, name='getSecTypesAll'),
url(r'^secTypes/Update/', equity.views.updateSecTypes, name='updateSecTypes'),
url(r'^secTypes/Delete/', equity.views.deleteSecTypes, name='deleteSecTypes'),
url(r'^secTypes/Create/', equity.views.createSecTypes, name='createSecTypes'),
to this:
url(r'^secTypesAll/', equity.views.getSecTypesAll, name='getSecTypesAll'),
url(r'^secTypes/Update/', equity.views.updateSecTypes, name='updateSecTypes'),
url(r'^secTypes/Delete/', equity.views.deleteSecTypes, name='deleteSecTypes'),
url(r'^secTypes/Create/', equity.views.createSecTypes, name='createSecTypes'),
url(r'^secTypes/', equity.views.getSecTypes, name='getSecTypes'),
The order matters when resolving URL patterns and if an earlier one matches, the following ones are not processed.
Both r'^secTypes/' and r'^secTypes/Update/' matches the string 'secTypes/Update/' so you need to be careful to put the more specific one first and the more general one afterwards.
Update the regex to match the end of the URL string by adding a $ like this:
url(r'^secTypes/$', equity.views.getSecTypes, name='getSecTypes'),
url(r'^secTypesAll/$', equity.views.getSecTypesAll, name='getSecTypesAll'),
url(r'^secTypes/Update/$', equity.views.updateSecTypes, name='updateSecTypes'),
url(r'^secTypes/Delete/$', equity.views.deleteSecTypes, name='deleteSecTypes'),
url(r'^secTypes/Create/$', equity.views.createSecTypes, name='createSecTypes'),
This is the preferred solution since it would stop Django from matching a URL like secTypes/Update/foobar
However, if you have logic in the view that specifically uses the substring after the end of the URL pattern (i.e. foobar based on the above example), this wouldn't work.

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: Permanent redirect of URL with regex parameters

I've been looking all over and can't find what I'm looking for.
I've found a way to redirect urls without parameters and keywords - but how to do it with parameters?
I want to redirect this:
(r'^andelsboligforeninger/(?P<page>[\d]*?)/$', 'cooperatives'),
to this:
(r'^liste-over-andelsboligforeninger/(?P<page>[\d]*?)/$', 'cooperatives'),
It should be a permanent redirect. This will be good for the SEO, and I get so many debug mails because of googlebot.
It seems I've found my answer in the django docs - I didn't look hard enought after all!
https://docs.djangoproject.com/en/1.1/ref/generic-views/
urlpatterns = patterns('django.views.generic.simple',
('^foo/(?P<id>\d+)/$', 'redirect_to', {'url': '/bar/%(id)s/'}),
)
First of all you need to do some changes in the url. Use url function and then give a name to the url. You have some issues in your url, for example you have used ?P but did'nt give a name to the capturing group. Second [\d]*? there is no need for ? because * means there can be a digit or not at all. So after considering all the above mentioned bugs and techniques in the end your url should look like this:
url(r'^liste-over-andelsboligforeninger/(?P<cooperative_id>\d*)/$', 'cooperatives', name="cooperatives")
Then in the view you can use reverse url resolution as:
redirect(reverse('cooperatives', kwargs={'cooperative_id': some_id}))