Changes between Version 2 and Version 4 of Ticket #28943
- Timestamp:
- Dec 20, 2017, 8:57:03 AM (7 years ago)
Legend:
- Unmodified
- Added
- Removed
- Modified
-
Ticket #28943
- Property Easy pickings unset
-
Ticket #28943 – Description
v2 v4 1 1 Currently, TemplateView inherits render_to_response(context) from TemplateResponseMixin which requires a context argument. 2 2 3 Instead, TemplateView should have its own render_to_response(context=None) that would get a context by default from get_context_data(). 3 This means that when your TemplateView subclass wants to return the TemplateResponse with the default context, you still have to create and pass the default context: 4 4 5 TemplateView.render_to_response() should call its ContextMixin.get_context_data() method automatically is because TemplateView inherits from both TemplateResponseMixin, and ContextMixin which provides the get_context_data() method. 5 {{{ 6 6 7 Currently, the workaround is to call 8 {{{ 9 # note usage of self in the method call 10 TemplateResponse.get(self, request, *args, **kwargs) 7 class YourView(TemplateView): 8 def post(self, request, *a, **k): 9 if not self.dostuff(): 10 return http.HttpResponseBadRequest() 11 12 context = self.get_context_data() 13 return self.render_to_response(context) 14 11 15 }}} 12 16 13 However, users should really be calling what they mean to do instead: 17 The reason for this is that ContentMixin defines get_context_data(), and TemplateResponseMixin defines render_to_response(context, ...), TemplateResponse mixes the two in get(): 14 18 15 19 {{{ 16 super().render_to_response() 20 class TemplateView(TemplateResponseMixin, ContextMixin, View): 21 """ 22 Render a template. Pass keyword arguments from the URLconf to the context. 23 """ 24 def get(self, request, *args, **kwargs): 25 context = self.get_context_data(**kwargs) 26 return self.render_to_response(context) 17 27 }}} 18 28 19 Then, then can still resolve {{ view }} in the template to add more variables. 29 I think it would be more usable as such: 30 31 32 {{{ 33 class TemplateView(TemplateResponseMixin, ContextMixin, View): 34 """ 35 Render a template. Pass keyword arguments from the URLconf to the context. 36 """ 37 def get(self, request, *args, **kwargs): 38 return self.render_to_response() 39 40 def render_to_response(self, context=None): 41 context = context or self.get_context_data(**kwargs) 42 return self.render_to_response(context) 43 }}} 44 45 Then, users could call render_to_response() in their code, ie: 46 47 {{{ 48 class YourView(TemplateView): 49 def get(self, request, *a, **k): 50 self.token = self.generatetoken() 51 return self.render_to_response() 52 53 def post(self, request, *a, **k): 54 if not self.dostuff(): 55 return http.HttpResponseBadRequest() 56 return super().render_to_response() 57 }}}.