2012-03-26 35 views
8

Tôi hiện đang có một DetailView cho tích hợp sẵn của Django User.Làm cách nào để thực hiện DetailView của người dùng ở Django?

url(
    r'^users/(?P<pk>\d+)/$', 
    DetailView.as_view(
     model = User, 
     template_name = 'doors/users/detail.html' 
    ), 
    name = 'users_detail' 
) 

Nhưng khi tôi truy cập user trong mẫu, nó sẽ trả về dòng điện đăng nhập sử dụng, không phải là người sử dụng với các pk mà tôi vượt qua từ DetailUser. Tôi có cần phải yêu cầu DetailUser đổi tên biến số user thành một biến khác không? Và nếu vậy, làm thế nào để tôi làm điều đó?

Trả lời

12

django.contrib.auth.context_processors.auth đặt biến ngữ cảnh mẫu {{ user }} thành request.user hoặc AnonymousUser. Vì vậy, nó sẽ ghi đè biến {{ user }} bối cảnh được tạo ra bởi DetailView của bạn:

def auth(request): 
    """ 
    Returns context variables required by apps that use Django's authentication 
    system. 

    If there is no 'user' attribute in the request, uses AnonymousUser (from 
    django.contrib.auth). 
    """ 
    # If we access request.user, request.session is accessed, which results in 
    # 'Vary: Cookie' being sent in every request that uses this context 
    # processor, which can easily be every request on a site if 
    # TEMPLATE_CONTEXT_PROCESSORS has this context processor added. This kills 
    # the ability to cache. So, we carefully ensure these attributes are lazy. 
    # We don't use django.utils.functional.lazy() for User, because that 
    # requires knowing the class of the object we want to proxy, which could 
    # break with custom auth backends. LazyObject is a less complete but more 
    # flexible solution that is a good enough wrapper for 'User'. 
    def get_user(): 
     if hasattr(request, 'user'): 
      return request.user 
     else: 
      from django.contrib.auth.models import AnonymousUser 
      return AnonymousUser() 

    return { 
     'user': SimpleLazyObject(get_user), 
     'messages': messages.get_messages(request), 
     'perms': lazy(lambda: PermWrapper(get_user()), PermWrapper)(), 
    } 

Bạn có thể làm việc xung quanh vấn đề bằng cách setting context_object_name. Ví dụ, điều này sẽ cho phép các biến {{ user_object }} bối cảnh, thiết lập cho người dùng của DetailView:

url(
    r'^users/(?P<pk>\d+)/$', 
    DetailView.as_view(
     model = User, 
     template_name = 'doors/users/detail.html', 
     context_object_name = 'user_object' 
    ), 
    name = 'users_detail' 
) 

Dig sâu hơn, đọc tài liệu cho get_context_object_name().

+0

Tôi không chắc chắn 100% về điều này, nhưng tôi đã có các chế độ xem chung khác và biến là tên của mô hình. Ví dụ, nếu tôi đã làm 'model = Poll' trong' ListView', thì biến sẽ trở thành 'poll_list'. Điều tương tự trong 'DetailView' cho một tên biến' poll'. Có lẽ đây là một cái gì đó mới trong Django v1.4? – hobbes3

+1

Bạn đã đúng, tôi đã sửa câu trả lời ở trên. Cảm ơn phản hôi của bạn ! – jpic

Các vấn đề liên quan