功能到基于类的视图(DetailView)Django

时间:2013-04-03 18:42:09

标签: django django-class-based-views django-1.5

所以我的基于功能的视图目前看起来像这样,我想把它改成基于类的视图

我的功能视图

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

我的基于班级的观点

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

我的网址

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

问题是,当我转到http://exampe.com/user/username网址时,我会收到匿名用户个人资料。我不希望这样。我必须在UserProfileDetail类上做出哪些更改?

提前谢谢

2 个答案:

答案 0 :(得分:1)

您已将slug_field = "username"添加到您的班级,但在此实例中不正确。在您的情况下,slug_field应该是"slug",因为the named group您已经为您的网址.../(?P<slug>[\w-]+)/...提供了用户名部分。 Django自动假设您的slug_field被称为slug,因此您只需删除行slug_field = "username"或将您的网址更改为:

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

答案 1 :(得分:1)

您需要覆盖context_object_name,因为默认情况下,django.contrib.auth.context_processors.auth会将{{ user }}模板上下文变量设置为request.userAnonymousUser。因此,您需要覆盖上下文

覆盖context_object_name

中的DetailView
# 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"

并在模板中使用

{{ user_profile }}