javascript - 如何在 Django 基于类的 View 中通过 mime-type 区分响应?

标签 javascript python django api rest

在基于类的 View 中,我可以定义 GETPOST 的方法。我可以以某种方式为不同的 mime 类型的响应定义特殊的方法吗?

用例是 - 即使 JS 关闭,也使 AJAX 站点可用。

最佳答案

import json

from django.http import HttpResponse
from django.views.generic.edit import CreateView
from myapp.models import Author

class AjaxableResponseMixin(object):
    """
    Mixin to add AJAX support to a form.
    Must be used with an object-based FormView (e.g. CreateView)
    """
    def render_to_json_response(self, context, **response_kwargs):
        data = json.dumps(context)
        response_kwargs['content_type'] = 'application/json'
        return HttpResponse(data, **response_kwargs)

    def form_invalid(self, form):
        response = super(AjaxableResponseMixin, self).form_invalid(form)
        if self.request.is_ajax():
            return self.render_to_json_response(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call form.save() for example).
        response = super(AjaxableResponseMixin, self).form_valid(form)
        if self.request.is_ajax():
            data = {
                'pk': self.object.pk,
            }
            return self.render_to_json_response(data)
        else:
            return response

class AuthorCreate(AjaxableResponseMixin, CreateView):
    model = Author
    fields = ['name']

看看文档中的这个示例: https://docs.djangoproject.com/en/dev/topics/class-based-views/generic-editing/#ajax-example

有两种情况:表单是否有效。 从这里我们有两种情况:请求是否基于 AJAX(request.is_ajax)

关于javascript - 如何在 Django 基于类的 View 中通过 mime-type 区分响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18302818/

相关文章:

javascript - 如何将 ViewModel Store 绑定(bind)到 View?

javascript - 将字符串作为属性传递给对象

javascript - 在reactjs中推荐的输入验证方法是什么

javascript - 使用 === 运算符来测试未定义而不是使用 == 运算符有什么好处?

python - 将 PDF 文件转换为 Base64 以索引到 Elasticsearch

python - 函数不打印所有偶数?

python - 调整等于 x 的列值的有效方法 - Python

python - 从 django url 传递 'start' 会出现错误 "start() takes exactly 2 arguments (1 given) "

python - 保存空条目的表单集

python - 成功执行 Django python 命令的*唯一*方法是使用 "python ...PATH...django-admin.py [options]"。为什么不能减少呢?