Ticket #18804: django-doc2.diff

File django-doc2.diff, 13.8 KB (added by anthonyb, 3 years ago)
  • docs/topics/class-based-views/index.txt

    diff --git a/docs/topics/class-based-views/index.txt b/docs/topics/class-based-views/index.txt
    index c2900ec..1f10935 100644
    a b to structure your views and reuse code by harnessing inheritance and 
    1111mixins. There are also some generic views for simple tasks which we'll
    1212get to later, but you may want to design your own structure of
    1313reusable views which suits your use case. For full details, see the
    14 :doc:`class-based views reference
    15 documentation</ref/class-based-views/index>`.
     14:doc:`class-based views reference documentation</ref/class-based-views/index>`.
    1615
    1716.. toctree::
    1817   :maxdepth: 1
    redirect, and :class:`~django.views.generic.base.TemplateView` extends the base 
    3231to make it also render a template.
    3332
    3433
    35 Simple usage
    36 ============
    37 
    38 Class-based generic views (and any class-based views that inherit from
    39 the base classes Django provides) can be configured in two
    40 ways: subclassing, or passing in arguments directly in the URLconf.
    41 
    42 When you subclass a class-based view, you can override attributes
    43 (such as the ``template_name``) or methods (such as ``get_context_data``)
    44 in your subclass to provide new values or methods. Consider, for example,
    45 a view that just displays one template, ``about.html``. Django has a
    46 generic view to do this - :class:`~django.views.generic.base.TemplateView` -
    47 so we can just subclass it, and override the template name::
    48 
    49     # some_app/views.py
    50     from django.views.generic import TemplateView
    51 
    52     class AboutView(TemplateView):
    53         template_name = "about.html"
    54 
    55 Then, we just need to add this new view into our URLconf. As the class-based
    56 views themselves are classes, we point the URL to the ``as_view`` class method
    57 instead, which is the entry point for class-based views::
    58 
    59     # urls.py
    60     from django.conf.urls import patterns, url, include
    61     from some_app.views import AboutView
    62 
    63     urlpatterns = patterns('',
    64         (r'^about/', AboutView.as_view()),
    65     )
     34Simple usage in your URLconf
     35============================
    6636
    67 Alternatively, if you're only changing a few simple attributes on a
    68 class-based view, you can simply pass the new attributes into the ``as_view``
    69 method call itself::
     37The simplest way to use generic views is to create them directly in your
     38URLconf. If you're only changing a few simple attributes on a class-based view,
     39you can simply pass them into the ``as_view`` method call itself::
    7040
    7141    from django.conf.urls import patterns, url, include
    7242    from django.views.generic import TemplateView
    method call itself:: 
    7545        (r'^about/', TemplateView.as_view(template_name="about.html")),
    7646    )
    7747
     48Any arguments given will override the ``template_name`` on the
    7849A similar overriding pattern can be used for the ``url`` attribute on
    7950:class:`~django.views.generic.base.RedirectView`.
    8051
    81 .. _jsonresponsemixin-example:
    82 
    83 More than just HTML
    84 -------------------
    85 
    86 Where class based views shine is when you want to do the same thing many times.
    87 Suppose you're writing an API, and every view should return JSON instead of
    88 rendered HTML.
    89 
    90 We can create a mixin class to use in all of our views, handling the
    91 conversion to JSON once.
    9252
    93 For example, a simple JSON mixin might look something like this::
     53Subclassing generic views
     54=========================
    9455
    95     import json
    96     from django.http import HttpResponse
     56The second, more powerful way to use generic views is to inherit from an
     57existing view and override attributes (such as the ``template_name``) or
     58methods (such as ``get_context_data``) in your subclass to provide new values
     59or methods. Consider, for example, a view that just displays one template,
     60``about.html``. Django has a generic view to do this -
     61:class:`~django.views.generic.base.TemplateView` - so we can just subclass it,
     62and override the template name::
    9763
    98     class JSONResponseMixin(object):
    99         """
    100         A mixin that can be used to render a JSON response.
    101         """
    102         response_class = HttpResponse
     64    # some_app/views.py
     65    from django.views.generic import TemplateView
    10366
    104         def render_to_response(self, context, **response_kwargs):
    105             """
    106             Returns a JSON response, transforming 'context' to make the payload.
    107             """
    108             response_kwargs['content_type'] = 'application/json'
    109             return self.response_class(
    110                 self.convert_context_to_json(context),
    111                 **response_kwargs
    112             )
     67    class AboutView(TemplateView):
     68        template_name = "about.html"
    11369
    114         def convert_context_to_json(self, context):
    115             "Convert the context dictionary into a JSON object"
    116             # Note: This is *EXTREMELY* naive; in reality, you'll need
    117             # to do much more complex handling to ensure that arbitrary
    118             # objects -- such as Django model instances or querysets
    119             # -- can be serialized as JSON.
    120             return json.dumps(context)
     70Then we just need to add this new view into our URLconf.
     71`~django.views.generic.base.TemplateView` is a class, not a function, so we
     72point the URL to the ``as_view`` class method instead, which provides a
     73function-like entry to class-based views::
    12174
    122 Now we mix this into the base TemplateView::
     75    # urls.py
     76    from django.conf.urls import patterns, url, include
     77    from some_app.views import AboutView
    12378
    124     from django.views.generic import TemplateView
     79    urlpatterns = patterns('',
     80        (r'^about/', AboutView.as_view()),
     81    )
    12582
    126     class JSONView(JSONResponseMixin, TemplateView):
    127         pass
    128 
    129 Equally we could use our mixin with one of the generic views. We can make our
    130 own version of :class:`~django.views.generic.detail.DetailView` by mixing
    131 :class:`JSONResponseMixin` with the
    132 :class:`~django.views.generic.detail.BaseDetailView` -- (the
    133 :class:`~django.views.generic.detail.DetailView` before template
    134 rendering behavior has been mixed in)::
    135 
    136     class JSONDetailView(JSONResponseMixin, BaseDetailView):
    137         pass
    138 
    139 This view can then be deployed in the same way as any other
    140 :class:`~django.views.generic.detail.DetailView`, with exactly the
    141 same behavior -- except for the format of the response.
    142 
    143 If you want to be really adventurous, you could even mix a
    144 :class:`~django.views.generic.detail.DetailView` subclass that is able
    145 to return *both* HTML and JSON content, depending on some property of
    146 the HTTP request, such as a query argument or a HTTP header. Just mix
    147 in both the :class:`JSONResponseMixin` and a
    148 :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`,
    149 and override the implementation of :func:`render_to_response()` to defer
    150 to the appropriate subclass depending on the type of response that the user
    151 requested::
    152 
    153     class HybridDetailView(JSONResponseMixin, SingleObjectTemplateResponseMixin, BaseDetailView):
    154         def render_to_response(self, context):
    155             # Look for a 'format=json' GET argument
    156             if self.request.GET.get('format','html') == 'json':
    157                 return JSONResponseMixin.render_to_response(self, context)
    158             else:
    159                 return SingleObjectTemplateResponseMixin.render_to_response(self, context)
    160 
    161 Because of the way that Python resolves method overloading, the local
    162 ``render_to_response()`` implementation will override the versions provided by
    163 :class:`JSONResponseMixin` and
    164 :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`.
    16583
    16684For more information on how to use the built in generic views, consult the next
    16785topic on :doc:`generic class based views</topics/class-based-views/generic-display>`.
    Decorating class-based views 
    17189
    17290.. highlightlang:: python
    17391
    174 The extension of class-based views isn't limited to using mixins. You
    175 can use also use decorators.
     92Since class-based views aren't functions, decorating them works differently
     93depending on if you're using ``as_view`` or want to apply the decorator
     94more widely.
    17695
    17796Decorating in URLconf
    17897---------------------
    17998
    18099The simplest way of decorating class-based views is to decorate the
    181100result of the :meth:`~django.views.generic.base.View.as_view` method.
    182 The easiest place to do this is in the URLconf where you deploy your
    183 view::
     101The easiest place to do this is in the URLconf where you deploy your view::
    184102
    185103    from django.contrib.auth.decorators import login_required, permission_required
    186104    from django.views.generic import TemplateView
    login protection. 
    231149    as parameters to the decorated method on the class. If your method
    232150    does not accept a compatible set of parameters it will raise a
    233151    ``TypeError`` exception.
     152
  • docs/topics/class-based-views/mixins.txt

    diff --git a/docs/topics/class-based-views/mixins.txt b/docs/topics/class-based-views/mixins.txt
    index 0c19d60..937a5fe 100644
    a b encapsulated in the 
    2727reference documentation contains :doc:`full documentation of all the
    2828mixins</ref/class-based-views/mixins>`.
    2929
     30
     31.. _jsonresponsemixin-example:
     32
     33More than just HTML
     34-------------------
     35
     36Where class based views shine is when you want to do the same thing many times.
     37Suppose you're writing an API, and every view should return JSON instead of
     38rendered HTML.
     39
     40We can create a mixin class to use in all of our views, handling the
     41conversion to JSON once.
     42
     43For example, a simple JSON mixin might look something like this::
     44
     45    import json
     46    from django.http import HttpResponse
     47
     48    class JSONResponseMixin(object):
     49        """
     50        A mixin that can be used to render a JSON response.
     51        """
     52        response_class = HttpResponse
     53
     54        def render_to_response(self, context, **response_kwargs):
     55            """
     56            Returns a JSON response, transforming 'context' to make the payload.
     57            """
     58            response_kwargs['content_type'] = 'application/json'
     59            return self.response_class(
     60                self.convert_context_to_json(context),
     61                **response_kwargs
     62            )
     63
     64        def convert_context_to_json(self, context):
     65            "Convert the context dictionary into a JSON object"
     66            # Note: This is *EXTREMELY* naive; in reality, you'll need
     67            # to do much more complex handling to ensure that arbitrary
     68            # objects -- such as Django model instances or querysets
     69            # -- can be serialized as JSON.
     70            return json.dumps(context)
     71
     72Now we mix this into the base TemplateView::
     73
     74    from django.views.generic import TemplateView
     75
     76    class JSONView(JSONResponseMixin, TemplateView):
     77        pass
     78
     79Equally we could use our mixin with one of the generic views. We can make our
     80own version of :class:`~django.views.generic.detail.DetailView` by mixing
     81:class:`JSONResponseMixin` with the
     82:class:`~django.views.generic.detail.BaseDetailView` -- (the
     83:class:`~django.views.generic.detail.DetailView` before template
     84rendering behavior has been mixed in)::
     85
     86    class JSONDetailView(JSONResponseMixin, BaseDetailView):
     87        pass
     88
     89This view can then be deployed in the same way as any other
     90:class:`~django.views.generic.detail.DetailView`, with exactly the
     91same behavior -- except for the format of the response.
     92
     93If you want to be really adventurous, you could even mix a
     94:class:`~django.views.generic.detail.DetailView` subclass that is able
     95to return *both* HTML and JSON content, depending on some property of
     96the HTTP request, such as a query argument or a HTTP header. Just mix
     97in both the :class:`JSONResponseMixin` and a
     98:class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`,
     99and override the implementation of :func:`render_to_response()` to defer
     100to the appropriate subclass depending on the type of response that the user
     101requested::
     102
     103    class HybridDetailView(JSONResponseMixin, SingleObjectTemplateResponseMixin, BaseDetailView):
     104        def render_to_response(self, context):
     105            # Look for a 'format=json' GET argument
     106            if self.request.GET.get('format','html') == 'json':
     107                return JSONResponseMixin.render_to_response(self, context)
     108            else:
     109                return SingleObjectTemplateResponseMixin.render_to_response(self, context)
     110
     111Because of the way that Python resolves method overloading, the local
     112``render_to_response()`` implementation will override the versions provided by
     113:class:`JSONResponseMixin` and
     114:class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`.
     115
     116
    30117Context and template responses
    31 ==============================
     118------------------------------
    32119
    33120Two central mixins are provided that help in providing a consistent
    34121interface to working with templates in class-based views.
    interface to working with templates in class-based views. 
    69156    add more members to the dictionary.
    70157
    71158Building up Django's generic class-based views
    72 ===============================================
     159----------------------------------------------
    73160
    74161Let's look at how two of Django's generic class-based views are built
    75162out of mixins providing discrete functionality. We'll consider
    covered in the :doc:`mixin reference 
    91178documentation</ref/class-based-views/mixins>`.
    92179
    93180DetailView: working with a single Django object
    94 -----------------------------------------------
     181===============================================
    95182
    96183To show the detail of an object, we basically need to do two things:
    97184we need to look up the object and then we need to make a
    views<generic-editing>` use ``_form`` for create and update views, and 
    128215``_confirm_delete`` for delete views.)
    129216
    130217ListView: working with many Django objects
    131 ------------------------------------------
     218==========================================
    132219
    133220Lists of objects follow roughly the same pattern: we need a (possibly
    134221paginated) list of objects, typically a :class:`QuerySet`, and then we need
Back to Top