5

나는 현재 django 1.3에서 클래스 기반 뷰를 사용하는 방법을 배우고있다. 나는 그들을 사용하기 위해 응용 프로그램을 업데이 트하려고하지만, 나는 그들이 잘 작동하는지 잘 이해하지 못한다 (그리고 나는 하루에 2-3 번 같은 전체 클래스 기반 뷰 참조를 읽는다).django 1.3에서 DetailView를 수행하는 방법?

질문에 나는 몇 가지 추가 컨텍스트 데이터가 필요한 공간 인덱스 페이지가 있습니다. url 매개 변수는 이름 (아무런 pk도없고 변경할 수 없으며 예상되는 동작입니다)이고 ' 자신의 프로필에서 선택한 공간을 입력 할 수 없습니다.

내 기능 기반 코드 (작업 고급) :

def view_space_index(request, space_name): 

    place = get_object_or_404(Space, url=space_name) 

    extra_context = { 
     'entities': Entity.objects.filter(space=place.id), 
     'documents': Document.objects.filter(space=place.id), 
     'proposals': Proposal.objects.filter(space=place.id).order_by('-pub_date'), 
     'publication': Post.objects.filter(post_space=place.id).order_by('-post_pubdate'), 
    } 

    for i in request.user.profile.spaces.all(): 
     if i.url == space_name: 
      return object_detail(request, 
           queryset = Space.objects.all(), 
           object_id = place.id, 
           template_name = 'spaces/space_index.html', 
           template_object_name = 'get_place', 
           extra_context = extra_context, 
           ) 

    return render_to_response('not_allowed.html', {'get_place': place}, 
           context_instance=RequestContext(request)) 

내 클래스 기반 뷰 (작동하지 않는, 계속하는 방법을 모르고) :

class ViewSpaceIndex(DetailView): 

    # Gets all the objects in a model 
    queryset = Space.objects.all() 

    # Get the url parameter intead of matching the PK 
    slug_field = 'space_name' 

    # Defines the context name in the template 
    context_object_name = 'get_place' 

    # Template to render 
    template_name = 'spaces/space_index.html' 

    def get_object(self): 
     return get_object_or_404(Space, url=slug_field) 

    # Get extra context data 
    def get_context_data(self, **kwargs): 
     context = super(ViewSpaceIndex, self).get_context_data(**kwargs) 
     place = self.get_object() 
     context['entities'] = Entity.objects.filter(space=place.id) 
     context['documents'] = Document.objects.filter(space=place.id) 
     context['proposals'] = Proposal.objects.filter(space=place.id).order_by('-pub_date') 
     context['publication'] = Post.objects.filter(post_space=place.id).order_by('-post_pubdate') 
     return context 

urls.py

from e_cidadania.apps.spaces.views import GoToSpace, ViewSpaceIndex 
urlpatterns = patterns('', 
    (r'^(?P<space_name>\w+)/', ViewSpaceIndex.as_view()), 
) 

DetailView가 작동하지 않는 이유는 무엇입니까?

답변

10

코드에서 볼 수있는 유일한 문제는 URL의 슬러그 매개 변수가 대신 'space_name'입니다. 보기의 slug_field 속성은 URL 캡처 이름이 아닌 슬러그 조회에 사용될 모델 필드를 참조합니다. URL에서 매개 변수의 이름을 'slug' (또는 대신 사용하는 경우 'pk')으로 지정해야합니다. 당신이 get_object 방법을 정의하는 경우 당신이 다른 곳에 당신의 get_object 또는에서 사용하지 않는

또한, 당신은 속성 queryset, model 또는 slug_field 필요하지 않습니다. 위의 경우

, 당신은 당신의 get_object 것은 당신이 쓴하거나 다음을 정의로 사용할 수 있습니다 중 하나 만 :

model = Space 
slug_field = 'space_name' 
+0

감사합니다! 바로 코드를 테스트 해 보겠습니다. –

관련 문제