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

前端 未结 5 970
小蘑菇
小蘑菇 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:47

    I found this elegant solution, and for django 1.5 or higher, as pointed out here:

    Django’s generic class based views now automatically include a view variable in the context. This variable points at your view object.

    In your views.py:

    from django.views.generic.base import TemplateView    
    
    class Yearly(TemplateView):
        template_name = "calendars/yearly.html"
        # Not here 
        current_year = datetime.datetime.now().year
        current_month = datetime.datetime.now().month
    
        # dispatch is called when the class instance loads
        def dispatch(self, request, *args, **kwargs):
            self.year = kwargs.get('year', "any_default")
    
        # other code
    
        # needed to have an HttpResponse
        return super(Yearly, self).dispatch(request, *args, **kwargs)
    

    The dispatch solution found in this question.
    As the view is already passed within Template context, you don't really need to worry about it. In your template file yearly.html, it is possible to access those view attributes simply by:

    {{ view.year }}
    {{ view.current_year }}
    {{ view.current_month }}
    

    You can keep your urlconf as it is.

    It's worth mentioning that getting information into your template’s context overwrites the get_context_data(), so it is somehow breaking the django's action bean flow.

提交回复
热议问题