in a mini virtual community, i have a profile_view function, so that i can view the profile of any registered user. The profile view function has as a parameter the id of th
Here's how I do it using class based generic views and the use of slugs. It's surprisingly easy and requires only a few lines of code with the help of slugs.
# accounts/views.py
from django.contrib.auth.models import User
from django.views.generic.detail import DetailView
class UserProfileView(DetailView):
model = User
slug_field = "username"
template_name = "userprofile.html"
# accounts/urls.py
from views import UserProfileView
urlpatterns = patterns('',
# By user ID
url(r'^profile/id/(?P\d+)/$', UserProfileView.as_view()),
# By username
url(r'^profile/username/(?P[\w.@+-]+)/$', UserProfileView.as_view()),
)
Now you can access both the user like accounts/profile/id/123/
as well as accounts/profile/username/gertvdijk/
.
What's happening here?
pk
URL parameter is omitted and replaced by slug
in the URL pattern. This is accepted by the view, because...User.username
by the use of model = User
and slug_field = "username"
. (docs)pk
parameter.