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

让人想犯罪 __ 提交于 2019-11-29 14:57:32

问题


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?


回答1:


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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!