Using Django class representations, how can I return another template if request.is_ajax

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

However, I want to use class-based views and rendering with a different template if request.is_ajax.

I don’t understand how I can redefine my template name "template_name" and make loading the template conditional in class-based views.

How can i do this?

+5
source share
2 answers

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

Ajax, get_template_names. , application/json, render_to_response, HttpResponse Ajax.

+4

get_template_names:

def get_template_names(self):
    if self.request.is_ajax():
        return ['ajax_template.html']
    else:
        return ['standard_template.html']
+9

All Articles