View not found for views with number at the end - python

I'm trying to do a reverse like this:
print reverse("shows-view")
This is in my urls.py:
url(r'^shows/(\d+)$', views.show_details, name="shows-view"),
Whenever I try to do that, it just returns:
Reverse for 'shows-view' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['shows/(\\d+)$']
But if I try to access the page directly (http://localhost/shows/3333) then it works fine
But if I do a reverse for other views like this:
print reverse("shows-default-view")
with the following declaration in the same urls.py file:
url(r'^shows/', views.popular, name="shows-default-view"),
then it works fine. Does anyone have any idea why?

The URL in question accepts an argument (\d+) which you are not passing your reverse function. Just think: this is a details view, but which show do you want to display?
To fix, call reverse with the args parameter:
reverse("shows-default-view", args=[1]) # to show show with id of 1
In general for URL's like that, the recommendation is to have a named captured group:
url(r'^shows/(?P<pk>\d+)$', views.show_details, name="shows-view")
And then the call to reverse will be:
reverse("shows-default-view", kwargs={'pk': 1})
To use reverse in a template, just put the two arguments together:
{% url 'shows-view' 1 %}

Related

Issue on Django Url Routers

I an trying to make url router in Django which supports following URLs :
http://localhost:8000/location/configuration
http://localhost:8000/location/d3d710fcfc1391b0a8182239881b8bf7/configuration
url(r'^locations/configuration$',
location_config.as_view(), name="location-config"),
url(r'^locations/(?P<location_key>[\w]+)/configuration$',
location_config.as_view(), name="location-config-uri")
Whenever I tried to hit http://localhost:8000/location/configuration, it picked up the second URL routing format instead of picking up first one.
Error:
TypeError at /locations/configuration/ get() missing 1 required
positional argument: 'location_key'
Can anyone help me here what goes wrong with the url routing format?
Nope, it does pick the first pattern which has no arguments, however you're using the same view in both patterns and location_config view has required argument location_key which is not provided when first pattern matches the URL. That's what error message is saying.
So write another view which will not require location_key argument or alter this view definition: add default to the parameter
def location_config(request, location_key=None):
....
now it is not a "required positional argument".
django Will look for a pk when you are using a detail view by default. you have to override it by using get_object()
in your case
def get_object(self, queryset=None):
location_key = self.kwargs.get('location_key')
obj = Model.objects.get(id=location_key)
return obj

Django NoReverseMatch for a Particular User

This is quite surprising and I can't seem to get my way around it.
The code below works for most users but it breaks when I try to render a link for user SSenior generating the error below:
NoReverseMatch at /tofollow/
Reverse for 'profile' with arguments '(u'SSenior ',)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['user/(?P\w+)/$']
urls.py
url(r'^tofollow/$', views.tofollow, name='tofollow'),
url(r'^user/(?P<username>\w+)/$', views.profile, name='profile'),
template.html
#{{user.username}}
The username has a space in the end of it.
u'SSenior '
The regex \w+ does not match spaces, therefore you get the NoReverseMatch error.
Remove the space (you could use the Django admin to do this) and it will work.

Reverse url lookup with include parameter

Does anyone know how to make a reverse url lookup on a url with an include parameter? For example I have the following url:
url(r'^photos/', include('photos.urls'), name="photos"),
And in my view i want to access it as follows
def photos_redirect(request, path):
return HttpResponsePermanentRedirect(reverse('photos') + path)
But it get the following error:
Reverse for 'photos' with arguments '()' and keyword arguments '{}' not found.
You have to reverse to a single urlpattern. The photos URL pattern is including all the urlpatterns in photos.urls, so you have to choose which single URL you are wanting to direct to.

django named url not picking variables

I have the following url pattern -
url(r'^detail/(?P<var>[\w]+)/(?P<var_slug>[\w-])/$', 'player_detail', name='player_detail'),
In my view, I have the following -
model_dict = {"player":PlayerProfile, "event":PlayerEvent, "need":PlayerNeed}
def player_list(request, var=None, var_slug=None):
'''
displays the list of vars
'''
objs = model_dict.get(var).objects.filter(slug=var_slug).order_by('-creation_time')[:20]
template_name = "list_"+str(var)+"s.html"
return render(request, template_name, {"objs":objs})
In my templates I finally do the following -
details of Player
The error I get is following -
Reverse for 'player_detail' with arguments '()' and keyword arguments '{u'var': u'baseball', u'slug': u'obj.slug'}' not found.
What am I missing?
also, is it a good way to pick models dynamically depending on the variable in the parameter, and generating a template name on the fly?
slug='obj.slug' should be slug=obj.slug
Your regex doesn't match a .
Also you probably want[\w-]+ just like your other regex.. one or more [\w or -]

Django Build URLs from template with integer param, the primary key

I have this link in a template:
Item 1
and this url in the urls.py
url(r'item/(?P<id>)/$', show_item, name="page_item")
however, this error occurs:
Reverse for 'show_item' with arguments '(63L,)' and keyword arguments '{}' not found.
I looked at this question:
how to get python to not append L to longs or ignore in django template
but it did not help.
Is there another way to use the primary key, which is an integer, in constructing URLs in templates?
The URL name doesn't match. Change the template to be:
Item 1
It should be page_item not show_item in template.

Categories