Ticket #18804: django-doc2.diff
File django-doc2.diff, 13.8 KB (added by , 12 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 11 11 mixins. There are also some generic views for simple tasks which we'll 12 12 get to later, but you may want to design your own structure of 13 13 reusable 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>`. 16 15 17 16 .. toctree:: 18 17 :maxdepth: 1 … … redirect, and :class:`~django.views.generic.base.TemplateView` extends the base 32 31 to make it also render a template. 33 32 34 33 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 ) 34 Simple usage in your URLconf 35 ============================ 66 36 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::37 The simplest way to use generic views is to create them directly in your 38 URLconf. If you're only changing a few simple attributes on a class-based view, 39 you can simply pass them into the ``as_view`` method call itself:: 70 40 71 41 from django.conf.urls import patterns, url, include 72 42 from django.views.generic import TemplateView … … method call itself:: 75 45 (r'^about/', TemplateView.as_view(template_name="about.html")), 76 46 ) 77 47 48 Any arguments given will override the ``template_name`` on the 78 49 A similar overriding pattern can be used for the ``url`` attribute on 79 50 :class:`~django.views.generic.base.RedirectView`. 80 51 81 .. _jsonresponsemixin-example:82 83 More than just HTML84 -------------------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 of88 rendered HTML.89 90 We can create a mixin class to use in all of our views, handling the91 conversion to JSON once.92 52 93 For example, a simple JSON mixin might look something like this:: 53 Subclassing generic views 54 ========================= 94 55 95 import json 96 from django.http import HttpResponse 56 The second, more powerful way to use generic views is to inherit from an 57 existing view and override attributes (such as the ``template_name``) or 58 methods (such as ``get_context_data``) in your subclass to provide new values 59 or 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, 62 and override the template name:: 97 63 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 103 66 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" 113 69 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) 70 Then 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 72 point the URL to the ``as_view`` class method instead, which provides a 73 function-like entry to class-based views:: 121 74 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 123 78 124 from django.views.generic import TemplateView 79 urlpatterns = patterns('', 80 (r'^about/', AboutView.as_view()), 81 ) 125 82 126 class JSONView(JSONResponseMixin, TemplateView):127 pass128 129 Equally we could use our mixin with one of the generic views. We can make our130 own version of :class:`~django.views.generic.detail.DetailView` by mixing131 :class:`JSONResponseMixin` with the132 :class:`~django.views.generic.detail.BaseDetailView` -- (the133 :class:`~django.views.generic.detail.DetailView` before template134 rendering behavior has been mixed in)::135 136 class JSONDetailView(JSONResponseMixin, BaseDetailView):137 pass138 139 This view can then be deployed in the same way as any other140 :class:`~django.views.generic.detail.DetailView`, with exactly the141 same behavior -- except for the format of the response.142 143 If you want to be really adventurous, you could even mix a144 :class:`~django.views.generic.detail.DetailView` subclass that is able145 to return *both* HTML and JSON content, depending on some property of146 the HTTP request, such as a query argument or a HTTP header. Just mix147 in both the :class:`JSONResponseMixin` and a148 :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`,149 and override the implementation of :func:`render_to_response()` to defer150 to the appropriate subclass depending on the type of response that the user151 requested::152 153 class HybridDetailView(JSONResponseMixin, SingleObjectTemplateResponseMixin, BaseDetailView):154 def render_to_response(self, context):155 # Look for a 'format=json' GET argument156 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 local162 ``render_to_response()`` implementation will override the versions provided by163 :class:`JSONResponseMixin` and164 :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`.165 83 166 84 For more information on how to use the built in generic views, consult the next 167 85 topic on :doc:`generic class based views</topics/class-based-views/generic-display>`. … … Decorating class-based views 171 89 172 90 .. highlightlang:: python 173 91 174 The extension of class-based views isn't limited to using mixins. You 175 can use also use decorators. 92 Since class-based views aren't functions, decorating them works differently 93 depending on if you're using ``as_view`` or want to apply the decorator 94 more widely. 176 95 177 96 Decorating in URLconf 178 97 --------------------- 179 98 180 99 The simplest way of decorating class-based views is to decorate the 181 100 result 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:: 101 The easiest place to do this is in the URLconf where you deploy your view:: 184 102 185 103 from django.contrib.auth.decorators import login_required, permission_required 186 104 from django.views.generic import TemplateView … … login protection. 231 149 as parameters to the decorated method on the class. If your method 232 150 does not accept a compatible set of parameters it will raise a 233 151 ``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 27 27 reference documentation contains :doc:`full documentation of all the 28 28 mixins</ref/class-based-views/mixins>`. 29 29 30 31 .. _jsonresponsemixin-example: 32 33 More than just HTML 34 ------------------- 35 36 Where class based views shine is when you want to do the same thing many times. 37 Suppose you're writing an API, and every view should return JSON instead of 38 rendered HTML. 39 40 We can create a mixin class to use in all of our views, handling the 41 conversion to JSON once. 42 43 For 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 72 Now we mix this into the base TemplateView:: 73 74 from django.views.generic import TemplateView 75 76 class JSONView(JSONResponseMixin, TemplateView): 77 pass 78 79 Equally we could use our mixin with one of the generic views. We can make our 80 own 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 84 rendering behavior has been mixed in):: 85 86 class JSONDetailView(JSONResponseMixin, BaseDetailView): 87 pass 88 89 This view can then be deployed in the same way as any other 90 :class:`~django.views.generic.detail.DetailView`, with exactly the 91 same behavior -- except for the format of the response. 92 93 If you want to be really adventurous, you could even mix a 94 :class:`~django.views.generic.detail.DetailView` subclass that is able 95 to return *both* HTML and JSON content, depending on some property of 96 the HTTP request, such as a query argument or a HTTP header. Just mix 97 in both the :class:`JSONResponseMixin` and a 98 :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`, 99 and override the implementation of :func:`render_to_response()` to defer 100 to the appropriate subclass depending on the type of response that the user 101 requested:: 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 111 Because 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 30 117 Context and template responses 31 ============================== 118 ------------------------------ 32 119 33 120 Two central mixins are provided that help in providing a consistent 34 121 interface to working with templates in class-based views. … … interface to working with templates in class-based views. 69 156 add more members to the dictionary. 70 157 71 158 Building up Django's generic class-based views 72 =============================================== 159 ---------------------------------------------- 73 160 74 161 Let's look at how two of Django's generic class-based views are built 75 162 out of mixins providing discrete functionality. We'll consider … … covered in the :doc:`mixin reference 91 178 documentation</ref/class-based-views/mixins>`. 92 179 93 180 DetailView: working with a single Django object 94 ----------------------------------------------- 181 =============================================== 95 182 96 183 To show the detail of an object, we basically need to do two things: 97 184 we need to look up the object and then we need to make a … … views<generic-editing>` use ``_form`` for create and update views, and 128 215 ``_confirm_delete`` for delete views.) 129 216 130 217 ListView: working with many Django objects 131 ------------------------------------------ 218 ========================================== 132 219 133 220 Lists of objects follow roughly the same pattern: we need a (possibly 134 221 paginated) list of objects, typically a :class:`QuerySet`, and then we need