I have a database and have the admin interface enabled. When I go to the admin interface and click on 'Users' there is one user whose username is ayman
. I am following a tutorial done in a book called 'Packt Publishing, Learning Website Development with Django'. Now, in my urls.py
, this is what I have.
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
url(r'^$', main_page),
url(r'^user/(\w+)/$', user_page),
)
In my views.py
, this is my user_page
def user_page(request, username):
try:
user = User.objects.get(username=username)
except:
raise Http404(username +' not found.')
bookmarks = user.bookmark_set.all()
variables = {
'username': username,
'bookmarks': bookmarks
}
return render(request, 'user_page.html', variables)
I am using the generic User
view to manage my users. When I go into the terminal and do
$python manage.py shell
and do
>>> from django.contrib.auth.models import User
>>> from bookmarks.models import *
>>> user = User.objects.get(id=1)
>>> user
<User: ayman>
>>> user.username
u'ayman'
as you can see, the username ayman
Does exist. Now, going back to the URLs and the user_page
view. In my web browser, I went to
127.0.0.1/user/ayman/
The urls.py
should capture ayman
and pass it as a parameter to user_page
, right? It does, but the user_page
view keeps raising the 404 error and it says ayman not found
. So the username
parameter in user_page
is in fact ayman
but it keeps failing the
user = User.objects.get(username=username)
even though ayman
is a username in my database. Any idea why?
You are using a bare except
clause, try except User.DoesNotExist
. The bare except
masks the real error, the missing import. Btw. there is also a shortcut for this:
from django.shortcuts import get_object_or_404
# ...
user = get_object_or_404(User, username=username)
The first argument is the model or a queryset, the following are all passed as keyword arguments to queryset.get()