以下代码实际上来自关于基于类的视图中的表单的 Django 文档:
import json
from django.http import HttpResponse
from django.views.generic.edit import CreateView
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):
if self.request.is_ajax():
return self.render_to_json_response(form.errors, status=400)
else:
return super(AjaxableResponseMixin, self).form_invalid(form)
def form_valid(self, form):
if self.request.is_ajax():
data = {
'pk': form.instance.pk,
}
return self.render_to_json_response(data)
else:
return super(AjaxableResponseMixin, self).form_valid(form)
class AuthorCreate(AjaxableResponseMixin, CreateView):
model = Author
我不明白的代码是super(AjaxableResponseMixin, self)
. 我知道super(ChildClass, self)
是用来在子类的代码中调用父类的方法的。但是AjaxableResponseMixin
没有父母!这是做什么的?