Using Django class-based views, how can I return a different template if request.is_ajax

前端 未结 2 878
醉梦人生
醉梦人生 2021-01-01 03:27

I find Django\'s request.is_ajax a very useful way to add progressive enhancement via JS and still keep DRY in my views.

However, I want to use class-based views and

相关标签:
2条回答
  • 2021-01-01 03:55

    The appropriate way to do this is to override the methods provided by the TemplateResponseMixin.

    If you simply need to provide a different template for Ajax requests, then override get_template_names. If you want to provide a different response altogether, say a application/json response, then override render_to_response to produce a different HttpResponse for Ajax requests.

    0 讨论(0)
  • 2021-01-01 04:02

    Override get_template_names:

    def get_template_names(self):
        if self.request.is_ajax():
            return ['ajax_template.html']
        else:
            return ['standard_template.html']
    
    0 讨论(0)
提交回复
热议问题