user2241826
user2241826

Reputation: 13

Function to Class Based View (DetailView) Django

So my function-base view currently looks like this, and I would like to change it to Class Based View

My Function View

def user_detail(request, username):
    try:
       user = User.objects.get(username=username)
    except User.DoesNotExist:
       raise Http404

My Class Based View

class UserProfileDetail(DetailView):
    model = User
    template_name = "profiles/user_detail.html"
    #use username instead of pk
    slug_field = "username"

My url

url(r"^user/(?P<slug>[\w-]+)/$", UserProfileDetail.as_view(), name="user_detail"),

The Problem is, when I go to the http://exampe.com/user/username url, I get the Anonymous user profile. I don't want that. What changes do I have to make on my UserProfileDetail class?

thank you in advance

Upvotes: 1

Views: 1465

Answers (2)

Iqbal
Iqbal

Reputation: 246

You need to override the context_object_name, because by default, django.contrib.auth.context_processors.auth sets {{ user }} template context variable to either request.user or AnonymousUser. So, you need to override the context

override the context_object_name from the DetailView class

# Detail Views
class UserDetailView(DetailView):
    model = User
    template_name = "profiles/user_detail.html"
    #use username instead of pk
    slug_field = "username"
    #override the context user object to user_profile
    context_object_name = "user_profile"

and in template use

{{ user_profile }}

Upvotes: 1

Timmy O&#39;Mahony
Timmy O&#39;Mahony

Reputation: 53998

You have added slug_field = "username" to your class which is incorrect in this instance. slug_field in your case should just be "slug" as that is the named group you have given the username part of your url: .../(?P<slug>[\w-]+)/.... Django automatically assumes that your slug_field is called slug so you can simply remove the line slug_field = "username" altogether or change your url to:

url(r"^user/(?P<username>[\w-]+)/$", UserProfileDetail.as_view(), name="user_detail"),

Upvotes: 1

Related Questions