使用基于 Django 类的视图,如果 request.is_ajax 如何返回不同的模板 [英] Using Django class-based views, how can I return a different template if request.is_ajax

查看:10
本文介绍了使用基于 Django 类的视图,如果 request.is_ajax 如何返回不同的模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 Django 的 request.is_ajax 是一种非常有用的方法,它可以通过 JS 添加渐进式增强功能,并且在我的视图中仍然保持 DRY.

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

但是,如果 request.is_ajax,我想使用基于类的视图并使用不同的模板进行渲染.

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

我不清楚如何覆盖默认的template_name"并在基于类的视图中使模板加载有条件.

It is not clear to me how I can override my default "template_name" and make the template loading conditional in class-based views.

我该怎么做?

推荐答案

适当的方法是覆盖 TemplateResponseMixin.

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

如果您只是需要为 Ajax 请求提供不同的模板,请覆盖 get_template_names.如果你想提供一个完全不同的响应,比如一个 application/json 响应,然后覆盖 render_to_response 来为 Ajax 请求生成一个不同的 HttpResponse.

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.

这篇关于使用基于 Django 类的视图,如果 request.is_ajax 如何返回不同的模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆