4

以下代码实际上来自关于基于类的视图中的表单的 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没有父母!这是做什么的?

4

1 回答 1

4

AuthorCreate,AjaxableResponseMixin的超类将是CreateView

>>> class a(object): pass
... 
>>> class b(object): pass
... 
>>> class c(a,b): pass
... 
>>> c.mro()
[<class '__main__.c'>, <class '__main__.a'>, <class '__main__.b'>, <type 'object'>]

mro()是“方法解析顺序”,super指的顺序。

于 2013-03-22T19:36:21.437 回答