URL-parameters and logic in Django class-based views (TemplateView)

前端 未结 5 978
小蘑菇
小蘑菇 2020-11-28 22:32

It is unclear to me how it is best to access URL-parameters in class-based-views in Django 1.5.

Consider the following:

View:



        
5条回答
  •  北荒
    北荒 (楼主)
    2020-11-28 22:57

    So far I've only been able to access these url parameters from within the get_queryset method, although I've only tried it with a ListView not a TemplateView. I'll use the url param to create an attribute on the object instance, then use that attribute in get_context_data to populate the context:

    class Yearly(TemplateView):
        template_name = "calendars/yearly.html"
    
        current_year = datetime.datetime.now().year
        current_month = datetime.datetime.now().month
    
        def get_queryset(self):
            self.year = self.kwargs['year']
            queryset = super(Yearly, self).get_queryset()
            return queryset
    
        def get_context_data(self, **kwargs):
            context = super(Yearly, self).get_context_data(**kwargs)
            context['current_year'] = self.current_year
            context['current_month'] = self.current_month
            context['year'] = self.year
            return context
    

提交回复
热议问题