1

所以我的基于函数的视图目前看起来像这样,我想将其更改为基于类的视图

我的功能视图

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 类进行哪些更改?

先感谢您

4

2 回答 2

1

您已添加slug_field = "username"到您的班级,在这种情况下不正确。slug_field在您的情况下,应该"slug"是您在 url: 中给出用户名部分的命名组.../(?P<slug>[\w-]+)/...。Django 自动假定你的slug_field被调用slug,所以你可以简单地完全删除该行slug_field = "username"或将你的 url 更改为:

url(r"^user/(?P<username>[\w-]+)/$", UserProfileDetail.as_view(), name="user_detail"),
于 2013-04-03T18:54:40.060 回答
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 }}
于 2013-04-04T16:50:22.453 回答