Django url patterns having reverse lookup issues with optional parameters - django

I am having some weird issues with reverse lookups. Here is my url scheme.
url(r'^overview/', 'ledger.views.overview', name='overview'),
url(r'^overview/(?P<tutorial>\w+)$', 'ledger.views.overview', name='overview_tutorial'),
When I call return redirect('overview_tutorial', tutorial='tutorial') it isn't loading the tutorial version, it is loading the regular version, which is weird to me. I thought by specifying the name of the url it would use that url but instead it is matching on the first url. Adding a $ to the end of the url scheme solves the problem:
url(r'^overview/$', 'ledger.views.overview', name='overview'),
url(r'^overview/(?P<tutorial>\w+)$', 'ledger.views.overview', name='overview_tutorial'),
but I still don't understand why it is doing this. What I really want to do is have a url scheme like this:
url(r'^overview/', 'ledger.views.overview', name='overview'),
url(r'^overview/(?P<tutorial>\w+)$', 'ledger.views.overview', name='overview_tutorial'),
url(r'^overview/(?P<success>\w+)$', 'ledger.views.overview', name='overview_success'),
url(r'^overview/(?P<error>\w+)$', 'ledger.views.overview', name='overview_error')
and then I can redirect to the appropriate appropriate url name and pass in the different parameters. ie:
return redirect('overview_success', success='True') #or
return redirect('overview_error', error='Login failed. Please try your username/password again')
but those both return as if I just called tutorial view. (which I am now realizing is because a reverse url lookup must build the url and then run it through the url patterns to see where it should direct to).
So then I tried doing this:
url(r'^overview/(?P<tutorial>\w+)$', 'ledger.views.overview', name='overview'),
url(r'^overview/(?P<tutorial>\w+)/(?P<success>\w+)$', 'ledger.views.overview', name='overview_success'),
url(r'^overview/(?P<tutorial>\w+)/(?P<success>\w+)/(?P<error>\w+)$', 'ledger.views.overview', name='overview_error'),
but when I call return redirect("overview_success", tutorial='', success="Hooray"), I again get an error:
Reverse for 'overview_success' with arguments '()' and keyword arguments '{'success': 'Hooray', 'tutorial': ''}' not found. 1 pattern(s) tried: ['overview/(?P<tutorial>\\w+)/(?P<success>\\w+)$']

It looks like you are trying to use your urlconf to accept messages that you want to send to the user. For example your error message
return redirect('overview_error', error='Login failed. Please try your username/password again')
However that's not what named groups in the urlconf are for. They are for matching url patterns to determine which view to render. So when you are calling redirect it isn't just sending you to a new url, it's resolving that url based on what you pass it.
In your second example your redirect call
return redirect("overview_success", tutorial='', success="Hooray")
is trying to match against your url pattern
url(r'^overview/(?P<tutorial>\w+)/(?P<success>\w+)$', 'ledger.views.overview', name='overview_success'),
as something like overview//Hooray which as you can see is not a valid pattern because of the empty string passed to tutorial which expects 1 or more "word" characters.
You can use the messaging framework to send messages to the user. https://docs.djangoproject.com/en/1.7/ref/contrib/messages/#module-django.contrib.messages

Related

Django - use redirect view with multiple parameters

Im trying to redirect to a view with multiple parameters:
in my urls.py (app exhibition) I have:
path('map/<float:lat>/<float:lng>/<int:zoom>', views.MapView.as_view(), name='map')
where float is defined in a path converter like this:
'[-+]?\d*\.?\d*'
For the redirection I have:
return redirect('exhibition:map', lat=48.128365,long=11.5662713,zoom=3)
After hours of trying and researching similar questions I still get:
Reverse for 'map' with keyword arguments '{'lat': 48.128365, 'long': 11.5662713, 'zoom': 3}' not found. 1 pattern(s) tried: ['de/map\\/(?P<lat>[-+]?\\d*\\.?\\d*)\\/(?P<lng>[-+]?\\d*\\.?\\d*)\\/(?P<zoom>[0-9]+)$']
If I adjust the url pattern and the redirect call to a single pattern (be it float or int) the redirection works. Thus the problem should be related to my usage of multiple parameters - but I just can see what is wrong.
Any hints welcome!
i guess it's typo, you have defined lng as second parameter in your path but in redirect statement you call it long, it should be
return redirect('exhibition:map', lat=48.128365, lng=11.5662713, zoom=3)

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.

django template throws NoReverseMatch error

I had two methods create and update in the views, in which update takes one argument whereas create does not take any. I have decided to turn them into only one function update_create because they were not that different.
This is how the new method in views looks:
def update_create(request, id=None):
This is my urls.py:
url(r'^(\d+)/update/$|create/$', update_create, name='update_create'),
This is how my template looks in templates/list.html
Create a new event
I got this error when using the above code:
NoReverseMatch at /agenda/list/
Reverse for 'update_create' with arguments '()' and keyword arguments '{}' not found.
But, if I use this in my templates instead (I have added an argument), it works without any errors:
Create a new event
Can someone explain what's happening? Why previous code didn't work, and Why the new code is working?
URL pattern (\d+) expects number to be provided as argument. To resolve the issue simply provide urls like this:
url(r'^(\d+)/update/$', update_create, name='update_create'),
url(r'^update/$', update_create, name='update_create'),
As mariodev pointed out, your url pattern was expecting a digit in front of the url. As such, your first url:
Create a new event
would generate a url like /update, which wasn't a valid url. However, the latter url:
Create a new event
would generate a url like /1/update, which was a valid url.
From the django docs: https://docs.djangoproject.com/en/dev/topics/http/urls/
Basically subsequent arguments get parsed on first come first serve, and passed to your view. Another thing to consider when developing is using explicitly named parameters, as the django docs elaborate on.

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