在基于类的视图中,我可以定义 forGET
或 for 的方法POST
。我可以以某种方式为不同的 mime 类型的响应定义特殊方法吗?
用例是 - 即使 JS 关闭,也使 AJAX 站点可用。
在基于类的视图中,我可以定义 forGET
或 for 的方法POST
。我可以以某种方式为不同的 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)