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 render with a different template if request.is_ajax.
It is not clear to me how I can override my default "template_name" and make the template loading conditional in class-based views.
How can I do this?
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.
Override get_template_names:
def get_template_names(self):
if self.request.is_ajax():
return ['ajax_template.html']
else:
return ['standard_template.html']
来源:https://stackoverflow.com/questions/11782025/using-django-class-based-views-how-can-i-return-a-different-template-if-request