Source

djangofrdoc / ref / class-based-views.txt

Full commit
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
=========================
Class-based generic views
=========================

.. versionadded:: 1.3

.. note::
    Prior to Django 1.3, generic views were implemented as functions. The
    function-based implementation has been deprecated in favor of the
    class-based approach described here.

    For details on the previous generic views implementation,
    see the :doc:`topic guide </topics/generic-views>` and
    :doc:`detailed reference </ref/generic-views>`.

Writing Web applications can be monotonous, because we repeat certain patterns
again and again. Django tries to take away some of that monotony at the model
and template layers, but Web developers also experience this boredom at the view
level.

A general introduction to class-based generic views can be found in the
:doc:`topic guide </topics/class-based-views>`.

This reference contains details of Django's built-in generic views, along with
a list of the keyword arguments that each generic view expects. Remember that
arguments may either come from the URL pattern or from the ``extra_context``
additional-information dictionary.

Most generic views require the ``queryset`` key, which is a ``QuerySet``
instance; see :doc:`/topics/db/queries` for more information about ``QuerySet``
objects.

Mixins
======

A mixin class is a way of using the inheritance capabilities of
classes to compose a class out of smaller pieces of behavior. Django's
class-based generic views are constructed by composing mixins into
usable generic views.

For example, the :class:`~django.views.generic.base.detail.DetailView`
is composed from:

    * :class:`~django.db.views.generic.base.View`, which provides the
      basic class-based behavior
    * :class:`~django.db.views.generic.detail.SingleObjectMixin`, which
      provides the utilities for retrieving and displaying a single object
    * :class:`~django.db.views.generic.detail.SingleObjectTemplateResponseMixin`,
      which provides the tools for rendering a single object into a
      template-based response.

When combined, these mixins provide all the pieces necessary to
provide a view over a single object that renders a template to produce
a response.

Django provides a range of mixins. If you want to write your own
generic views, you can build classes that compose these mixins in
interesting ways. Alternatively, you can just use the pre-mixed
`Generic views`_ that Django provides.

.. note::

    When the documentation for a view gives the list of mixins, that view
    inherits all the properties and methods of that mixin.

Simple mixins
-------------

.. currentmodule:: django.views.generic.base

TemplateResponseMixin
~~~~~~~~~~~~~~~~~~~~~
.. class:: TemplateResponseMixin()

    .. attribute:: template_name

        The path to the template to use when rendering the view.

    .. attribute:: response_class

        The response class to be returned by ``render_to_response`` method.
        Default is
        :class:`TemplateResponse <django.template.response.TemplateResponse>`.
        The template and context of TemplateResponse instances can be
        altered later (e.g. in
        :ref:`template response middleware <template-response-middleware>`).

        Create TemplateResponse subclass and pass set it to
        ``template_response_class`` if you need custom template loading or
        custom context object instantiation.

    .. method:: render_to_response(context, **response_kwargs)

        Returns a ``self.template_response_class`` instance.

        If any keyword arguments are provided, they will be
        passed to the constructor of the response instance.

        Calls :meth:`~TemplateResponseMixin.get_template_names()` to obtain the
        list of template names that will be searched looking for an existent
        template.

    .. method:: get_template_names()

        Returns a list of template names to search for when rendering the
        template.

        If :attr:`TemplateResponseMixin.template_name` is specified, the
        default implementation will return a list containing
        :attr:`TemplateResponseMixin.template_name` (if it is specified).


Single object mixins
--------------------

.. currentmodule:: django.views.generic.detail

SingleObjectMixin
~~~~~~~~~~~~~~~~~
.. class:: SingleObjectMixin()

    .. attribute:: model

        The model that this view will display data for. Specifying ``model
        = Foo`` is effectively the same as specifying ``queryset =
        Foo.objects.all()``.

    .. attribute:: queryset

        A ``QuerySet`` that represents the objects. If provided, the value of
        :attr:`SingleObjectMixin.queryset` supersedes the value provided for
        :attr:`SingleObjectMixin.model`.

    .. attribute:: slug_field

        The name of the field on the model that contains the slug. By default,
        ``slug_field`` is ``'slug'``.

    .. attribute:: context_object_name

        Designates the name of the variable to use in the context.

    .. method:: get_object(queryset=None)

        Returns the single object that this view will display. If
        ``queryset`` is provided, that queryset will be used as the
        source of objects; otherwise,
        :meth:`~SingleObjectMixin.get_queryset` will be used.
        :meth:`~SingleObjectMixin.get_object` looks for a ``pk``
        argument in the arguments to the view; if ``pk`` is found,
        this method performs a primary-key based lookup using that
        value. If no ``pk`` argument is found, it looks for a ``slug``
        argument, and performs a slug lookup using the
        :attr:`SingleObjectMixin.slug_field`.

    .. method:: get_queryset()

        Returns the queryset that will be used to retrieve the object that
        this view will display. By default,
        :meth:`~SingleObjectMixin.get_queryset` returns the value of the
        :attr:`~SingleObjectMixin.queryset` attribute if it is set, otherwise
        it constructs a :class:`QuerySet` by calling the `all()` method on the
        :attr:`~SingleObjectMixin.model` attribute's default manager.

    .. method:: get_context_object_name(obj)

        Return the context variable name that will be used to contain the
        data that this view is manipulating. If
        :attr:`~SingleObjectMixin.context_object_name` is not set, the context
        name will be constructed from the ``object_name`` of the model that
        the queryset is composed from. For example, the model ``Article``
        would have context object named ``'article'``.

    .. method:: get_context_data(**kwargs)

        Returns context data for displaying the list of objects.

    **Context**

        * ``object``: The object that this view is displaying. If
          ``context_object_name`` is specified, that variable will also be
          set in the context, with the same value as ``object``.

SingleObjectTemplateResponseMixin
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. class:: SingleObjectTemplateResponseMixin()

    A mixin class that performs template-based response rendering for views
    that operate upon a single object instance. Requires that the view it is
    mixed with provides ``self.object``, the object instance that the view is
    operating on. ``self.object`` will usually be, but is not required to be,
    an instance of a Django model. It may be ``None`` if the view is in the
    process of constructing a new instance.

    **Extends**

        * :class:`~django.views.generic.base.TemplateResponseMixin`

    .. attribute:: template_name_field

        The field on the current object instance that can be used to determine
        the name of a candidate template. If either ``template_name_field`` or
        the value of the ``template_name_field`` on the current object instance
        is ``None``, the object will not be interrogated for a candidate
        template name.

    .. attribute:: template_name_suffix

        The suffix to append to the auto-generated candidate template name.
        Default suffix is ``_detail``.

    .. method:: get_template_names()

        Returns a list of candidate template names. Returns the following list:

          * the value of ``template_name`` on the view (if provided)
          * the contents of the ``template_name_field`` field on the
            object instance that the view is operating upon (if available)
          * ``<app_label>/<object_name><template_name_suffix>.html``

Multiple object mixins
----------------------

.. currentmodule:: django.views.generic.list

MultipleObjectMixin
~~~~~~~~~~~~~~~~~~~
.. class:: MultipleObjectMixin()

    A mixin that can be used to display a list of objects.

    If ``paginate_by`` is specified, Django will paginate the results returned
    by this. You can specify the page number in the URL in one of two ways:

        * Use the ``page`` parameter in the URLconf. For example, this is what
          your URLconf might look like::

            (r'^objects/page(?P<page>[0-9]+)/$', PaginatedView.as_view())

        * Pass the page number via the ``page`` query-string parameter. For
          example, a URL would look like this::

            /objects/?page=3

    These values and lists are 1-based, not 0-based, so the first page would be
    represented as page ``1``.

    For more on pagination, read the :doc:`pagination documentation
    </topics/pagination>`.

    As a special case, you are also permitted to use ``last`` as a value for
    ``page``::

        /objects/?page=last

    This allows you to access the final page of results without first having to
    determine how many pages there are.

    Note that ``page`` *must* be either a valid page number or the value
    ``last``; any other value for ``page`` will result in a 404 error.

    .. attribute:: allow_empty

        A boolean specifying whether to display the page if no objects are
        available. If this is ``False`` and no objects are available, the view
        will raise a 404 instead of displaying an empty page. By default, this
        is ``True``.

    .. attribute:: model

        The model that this view will display data for. Specifying ``model
        = Foo`` is effectively the same as specifying ``queryset =
        Foo.objects.all()``.

    .. attribute:: queryset

        A ``QuerySet`` that represents the objects. If provided, the value of
        :attr:`MultipleObjectMixin.queryset` supersedes the value provided for
        :attr:`MultipleObjectMixin.model`.

    .. attribute:: paginate_by

        An integer specifying how many objects should be displayed per page. If
        this is given, the view will paginate objects with
        :attr:`MultipleObjectMixin.paginate_by` objects per page. The view will
        expect either a ``page`` query string parameter (via ``GET``) or a
        ``page`` variable specified in the URLconf.

    .. attribute:: paginator_class

       The paginator class to be used for pagination. By default,
       :class:`django.core.paginator.Paginator` is used. If the custom paginator
       class doesn't have the same constructor interface as
       :class:`django.core.paginator.Paginator`, you will also need to
       provide an implementation for :meth:`MultipleObjectMixin.get_paginator`.

    .. attribute:: context_object_name

        Designates the name of the variable to use in the context.

    .. method:: get_queryset()

        Returns the queryset that represents the data this view will display.

    .. method:: paginate_queryset(queryset, page_size)

        Returns a 4-tuple containing (``paginator``, ``page``, ``object_list``,
        ``is_paginated``).

        Constructed by paginating ``queryset`` into pages of size ``page_size``.
        If the request contains a ``page`` argument, either as a captured URL
        argument or as a GET argument, ``object_list`` will correspond to the
        objects from that page.

    .. method:: get_paginate_by(queryset)

        Returns the number of items to paginate by, or ``None`` for no
        pagination. By default this simply returns the value of
        :attr:`MultipleObjectMixin.paginate_by`.

    .. method:: get_paginator(queryset, per_page, orphans=0, allow_empty_first_page=True)

        Returns an instance of the paginator to use for this view. By default,
        instantiates an instance of :attr:`paginator_class`.

    .. method:: get_allow_empty()

        Return a boolean specifying whether to display the page if no objects
        are available. If this method returns ``False`` and no objects are
        available, the view will raise a 404 instead of displaying an empty
        page. By default, this is ``True``.

    .. method:: get_context_object_name(object_list)

        Return the context variable name that will be used to contain
        the list of data that this view is manipulating. If
        ``object_list`` is a queryset of Django objects and
        :attr:`~MultipleObjectMixin.context_object_name` is not set,
        the context name will be the ``object_name`` of the model that
        the queryset is composed from, with postfix ``'_list'``
        appended. For example, the model ``Article`` would have a
        context object named ``article_list``.

    .. method:: get_context_data(**kwargs)

        Returns context data for displaying the list of objects.

    **Context**

        * ``object_list``: The list of objects that this view is displaying. If
          ``context_object_name`` is specified, that variable will also be set
          in the context, with the same value as ``object_list``.

        * ``is_paginated``: A boolean representing whether the results are
          paginated. Specifically, this is set to ``False`` if no page size has
          been specified, or if the available objects do not span multiple
          pages.

        * ``paginator``: An instance of
          :class:`django.core.paginator.Paginator`. If the page is not
          paginated, this context variable will be ``None``.

        * ``page_obj``: An instance of
          :class:`django.core.paginator.Page`. If the page is not paginated,
          this context variable will be ``None``.

MultipleObjectTemplateResponseMixin
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.. class:: MultipleObjectTemplateResponseMixin()

    A mixin class that performs template-based response rendering for views
    that operate upon a list of object instances. Requires that the view it is
    mixed with provides ``self.object_list``, the list of object instances that
    the view is operating on. ``self.object_list`` may be, but is not required
    to be, a :class:`~django.db.models.Queryset`.

    **Extends**

        * :class:`~django.views.generic.base.TemplateResponseMixin`

    .. attribute:: template_name_suffix

        The suffix to append to the auto-generated candidate template name.
        Default suffix is ``_list``.

    .. method:: get_template_names()

        Returns a list of candidate template names. Returns the following list:

          * the value of ``template_name`` on the view (if provided)
          * ``<app_label>/<object_name><template_name_suffix>.html``

Editing mixins
--------------

.. currentmodule:: django.views.generic.edit

FormMixin
~~~~~~~~~
.. class:: FormMixin()

    A mixin class that provides facilities for creating and displaying forms.

    .. attribute:: initial

        A dictionary containing initial data for the form.

    .. attribute:: form_class

        The form class to instantiate.

    .. attribute:: success_url

        The URL to redirect to when the form is successfully processed.

    .. method:: get_initial()

        Retrieve initial data for the form. By default, returns
        :attr:`.initial`.

    .. method:: get_form_class()

        Retrieve the form class to instantiate. By default
        :attr:`.form_class`.

    .. method:: get_form(form_class)

        Instantiate an instance of ``form_class`` using
        :meth:`.get_form_kwargs`.

    .. method:: get_form_kwargs()

        Build the keyword arguments requried to instanciate an the form.

        The ``initial`` argument is set to :meth:`.get_initial`. If the
        request is a ``POST`` or ``PUT``, the request data (``request.POST``
        and ``request.FILES``) will also be provided.

    .. method:: get_success_url()

        Determine the URL to redirect to when the form is successfully
        validated. Returns :attr:`.success_url` by default.

    .. method:: form_valid(form)

        Redirects to :meth:`.get_success_url`.

    .. method:: form_invalid(form)

        Renders a response, providing the invalid form as context.

    .. method:: get_context_data(**kwargs)

        Populates a context containing the contents of ``kwargs``.

    **Context**

        * ``form``: The form instance that was generated for the view.

    .. note::

        Views mixing :class:`FormMixin` must
        provide an implementation of :meth:`.form_valid` and
        :meth:`.form_invalid`.

ModelFormMixin
~~~~~~~~~~~~~~
.. class:: ModelFormMixin()

    A form mixin that works on ModelForms, rather than a standalone form.

    Since this is a subclass of
    :class:`~django.views.generic.detail.SingleObjectMixin`, instances of this
    mixin have access to the :attr:`~SingleObjectMixin.model` and
    :attr:`~SingleObjectMixin.queryset` attributes, describing the type of
    object that the ModelForm is manipulating. The view also provides
    ``self.object``, the instance being manipulated. If the instance is being
    created, ``self.object`` will be ``None``

    **Mixins**

        * :class:`django.views.generic.edit.FormMixin`
        * :class:`django.views.generic.detail.SingleObjectMixin`

    .. attribute:: success_url

        The URL to redirect to when the form is successfully processed.

        ``success_url`` may contain dictionary string formatting, which
        will be interpolated against the object's field attributes. For
        example, you could use ``success_url="/polls/%(slug)s/"`` to
        redirect to a URL composed out of the ``slug`` field on a model.

    .. method:: get_form_class()

        Retrieve the form class to instantiate. If
        :attr:`FormMixin.form_class` is provided, that class will be used.
        Otherwise, a ModelForm will be instantiated using the model associated
        with the :attr:`~SingleObjectMixin.queryset`, or with the
        :attr:`~SingleObjectMixin.model`, depending on which attribute is
        provided.

    .. method:: get_form_kwargs()

        Add the current instance (``self.object``) to the standard
        :meth:`FormMixin.get_form_kwargs`.

    .. method:: get_success_url()

        Determine the URL to redirect to when the form is successfully
        validated. Returns :attr:`FormMixin.success_url` if it is provided;
        otherwise, attempts to use the ``get_absolute_url()`` of the object.

    .. method:: form_valid()

        Saves the form instance, sets the current object for the view, and
        redirects to :meth:`.get_success_url`.

    .. method:: form_invalid()

        Renders a response, providing the invalid form as context.

ProcessFormView
~~~~~~~~~~~~~~~
.. class:: ProcessFormView()

    A mixin that provides basic HTTP GET and POST workflow.

    .. method:: get(request, *args, **kwargs)

        Constructs a form, then renders a response using a context that
        contains that form.

    .. method:: post(request, *args, **kwargs)

        Constructs a form, checks the form for validity, and handles it
        accordingly.

    The PUT action is also handled, as an analog of POST.

DeletionMixin
~~~~~~~~~~~~~
.. class:: DeletionMixin()

    Enables handling of the ``DELETE`` http action.

    .. attribute:: success_url

        The url to redirect to when the nominated object has been
        successfully deleted.

    .. method:: get_success_url(obj)

        Returns the url to redirect to when the nominated object has been
        successfully deleted. Returns
        :attr:`~django.views.generic.edit.DeletionMixin.success_url` by
        default.

Date-based mixins
-----------------

.. currentmodule:: django.views.generic.dates

YearMixin
~~~~~~~~~
.. class:: YearMixin()

    A mixin that can be used to retrieve and provide parsing information for a
    year component of a date.

    .. attribute:: year_format

        The strftime_ format to use when parsing the year. By default, this is
        ``'%Y'``.

    .. _strftime: http://docs.python.org/library/time.html#time.strftime

    .. attribute:: year

        **Optional** The value for the year (as a string). By default, set to
        ``None``, which means the year will be determined using other means.

    .. method:: get_year_format()

        Returns the strftime_ format to use when parsing the year. Returns
        :attr:`YearMixin.year_format` by default.

    .. method:: get_year()

        Returns the year for which this view will display data. Tries the
        following sources, in order:

            * The value of the :attr:`YearMixin.year` attribute.
            * The value of the `year` argument captured in the URL pattern
            * The value of the `year` GET query argument.

        Raises a 404 if no valid year specification can be found.

MonthMixin
~~~~~~~~~~
.. class:: MonthMixin()

    A mixin that can be used to retrieve and provide parsing information for a
    month component of a date.

    .. attribute:: month_format

        The strftime_ format to use when parsing the month. By default, this is
        ``'%b'``.

    .. attribute:: month

        **Optional** The value for the month (as a string). By default, set to
        ``None``, which means the month will be determined using other means.

    .. method:: get_month_format()

        Returns the strftime_ format to use when parsing the month. Returns
        :attr:`MonthMixin.month_format` by default.

    .. method:: get_month()

        Returns the month for which this view will display data. Tries the
        following sources, in order:

            * The value of the :attr:`MonthMixin.month` attribute.
            * The value of the `month` argument captured in the URL pattern
            * The value of the `month` GET query argument.

        Raises a 404 if no valid month specification can be found.

    .. method:: get_next_month(date)

        Returns a date object containing the first day of the month after the
        date provided. Returns ``None`` if mixed with a view that sets
        ``allow_future = False``, and the next month is in the future. If
        ``allow_empty = False``, returns the next month that contains data.

    .. method:: get_prev_month(date)

        Returns a date object containing the first day of the month before the
        date provided. If ``allow_empty = False``, returns the previous month
        that contained data.

DayMixin
~~~~~~~~~
.. class:: DayMixin()

    A mixin that can be used to retrieve and provide parsing information for a
    day component of a date.

    .. attribute:: day_format

        The strftime_ format to use when parsing the day. By default, this is
        ``'%d'``.

    .. attribute:: day

        **Optional** The value for the day (as a string). By default, set to
        ``None``, which means the day will be determined using other means.

    .. method:: get_day_format()

        Returns the strftime_ format to use when parsing the day. Returns
        :attr:`DayMixin.day_format` by default.

    .. method:: get_day()

        Returns the day for which this view will display data. Tries the
        following sources, in order:

            * The value of the :attr:`DayMixin.day` attribute.
            * The value of the `day` argument captured in the URL pattern
            * The value of the `day` GET query argument.

        Raises a 404 if no valid day specification can be found.

    .. method:: get_next_day(date)

        Returns a date object containing the next day after the date provided.
        Returns ``None`` if mixed with a view that sets ``allow_future = False``,
        and the next day is in the future. If ``allow_empty = False``, returns
        the next day that contains data.

    .. method:: get_prev_day(date)

        Returns a date object containing the previous day. If
        ``allow_empty = False``, returns the previous day that contained data.

WeekMixin
~~~~~~~~~
.. class:: WeekMixin()

    A mixin that can be used to retrieve and provide parsing information for a
    week component of a date.

    .. attribute:: week_format

        The strftime_ format to use when parsing the week. By default, this is
        ``'%U'``.

    .. attribute:: week

        **Optional** The value for the week (as a string). By default, set to
        ``None``, which means the week will be determined using other means.

    .. method:: get_week_format()

        Returns the strftime_ format to use when parsing the week. Returns
        :attr:`WeekMixin.week_format` by default.

    .. method:: get_week()

        Returns the week for which this view will display data. Tries the
        following sources, in order:

            * The value of the :attr:`WeekMixin.week` attribute.
            * The value of the `week` argument captured in the URL pattern
            * The value of the `week` GET query argument.

        Raises a 404 if no valid week specification can be found.


DateMixin
~~~~~~~~~
.. class:: DateMixin()

    A mixin class providing common behavior for all date-based views.

    .. attribute:: date_field

        The name of the ``DateField`` or ``DateTimeField`` in the
        ``QuerySet``'s model that the date-based archive should use to
        determine the objects on the page.

    .. attribute:: allow_future

        A boolean specifying whether to include "future" objects on this page,
        where "future" means objects in which the field specified in
        ``date_field`` is greater than the current date/time. By default, this
        is ``False``.

    .. method:: get_date_field()

        Returns the name of the field that contains the date data that this
        view will operate on. Returns :attr:`DateMixin.date_field` by default.

    .. method:: get_allow_future()

        Determine whether to include "future" objects on this page, where
        "future" means objects in which the field specified in ``date_field``
        is greater than the current date/time. Returns
        :attr:`DateMixin.date_field` by default.

BaseDateListView
~~~~~~~~~~~~~~~~
.. class:: BaseDateListView()

    A base class that provides common behavior for all date-based views. There
    won't normally be a reason to instantiate
    :class:`~django.views.generic.dates.BaseDateListView`; instantiate one of
    the subclasses instead.

    While this view (and it's subclasses) are executing, ``self.object_list``
    will contain the list of objects that the view is operating upon, and
    ``self.date_list`` will contain the list of dates for which data is
    available.

    **Mixins**

        * :class:`~django.views.generic.dates.DateMixin`
        * :class:`~django.views.generic.list.MultipleObjectMixin`

    .. attribute:: allow_empty

        A boolean specifying whether to display the page if no objects are
        available. If this is ``False`` and no objects are available, the view
        will raise a 404 instead of displaying an empty page. By default, this
        is ``True``.

    .. method:: get_dated_items():

        Returns a 3-tuple containing (``date_list``, ``latest``,
        ``extra_context``).

        ``date_list`` is the list of dates for which data is available.
        ``object_list`` is the list of objects ``extra_context`` is a
        dictionary of context data that will be added to any context data
        provided by the
        :class:`~django.views.generic.list.MultipleObjectMixin`.

    .. method:: get_dated_queryset(**lookup)

        Returns a queryset, filtered using the query arguments defined by
        ``lookup``. Enforces any restrictions on the queryset, such as
        ``allow_empty`` and ``allow_future``.

    .. method:: get_date_list(queryset, date_type)

        Returns the list of dates of type ``date_type`` for which
        ``queryset`` contains entries. For example, ``get_date_list(qs,
        'year')`` will return the list of years for which ``qs`` has entries.
        See :meth:`~django.db.models.QuerySet.dates()` for the
        ways that the ``date_type`` argument can be used.


Generic views
=============

Simple generic views
--------------------

.. currentmodule:: django.views.generic.base

View
~~~~
.. class:: View()

    The master class-based base view. All other generic class-based views
    inherit from this base class.

    Each request served by a :class:`~django.views.generic.base.View` has an
    independent state; therefore, it is safe to store state variables on the
    instance (i.e., ``self.foo = 3`` is a thread-safe operation).

    A class-based view is deployed into a URL pattern using the
    :meth:`~View.as_view()` classmethod::

        urlpatterns = patterns('',
                (r'^view/$', MyView.as_view(size=42)),
            )

    Any argument passed into :meth:`~View.as_view()` will be assigned onto the
    instance that is used to service a request. Using the previous example,
    this means that every request on ``MyView`` is able to interrogate
    ``self.size``.

    .. admonition:: Thread safety with view arguments

        Arguments passed to a view are shared between every instance of a view.
        This means that you shoudn't use a list, dictionary, or any other
        variable object as an argument to a view. If you did, the actions of
        one user visiting your view could have an effect on subsequent users
        visiting the same view.

    .. method:: dispatch(request, *args, **kwargs)

        The ``view`` part of the view -- the method that accepts a ``request``
        argument plus arguments, and returns a HTTP response.

        The default implementation will inspect the HTTP method and attempt to
        delegate to a method that matches the HTTP method; a ``GET`` will be
        delegated to :meth:`~View.get()`, a ``POST`` to :meth:`~View.post()`,
        and so on.

        The default implementation also sets ``request``, ``args`` and
        ``kwargs`` as instance variables, so any method on the view can know
        the full details of the request that was made to invoke the view.

    .. method:: http_method_not_allowed(request, *args, **kwargs)

        If the view was called with HTTP method it doesn't support, this method
        is called instead.

        The default implementation returns ``HttpResponseNotAllowed`` with list
        of allowed methods in plain text.

TemplateView
~~~~~~~~~~~~
.. class:: TemplateView()

    Renders a given template, passing it a ``{{ params }}`` template variable,
    which is a dictionary of the parameters captured in the URL.

    **Mixins**

        * :class:`django.views.generic.base.TemplateResponseMixin`

    .. attribute:: template_name

        The full name of a template to use.

    .. method:: get_context_data(**kwargs)

        Return a context data dictionary consisting of the contents of
        ``kwargs`` stored in the context variable ``params``.

    **Context**

        * ``params``: The dictionary of keyword arguments captured from the URL
          pattern that served the view.

RedirectView
~~~~~~~~~~~~
.. class:: RedirectView()

    Redirects to a given URL.

    The given URL may contain dictionary-style string formatting, which will be
    interpolated against the parameters captured in the URL. Because keyword
    interpolation is *always* done (even if no arguments are passed in), any
    ``"%"`` characters in the URL must be written as ``"%%"`` so that Python
    will convert them to a single percent sign on output.

    If the given URL is ``None``, Django will return an ``HttpResponseGone``
    (410).

    .. attribute:: url

        The URL to redirect to, as a string. Or ``None`` to raise a 410 (Gone)
        HTTP error.

    .. attribute:: permanent

        Whether the redirect should be permanent. The only difference here is
        the HTTP status code returned. If ``True``, then the redirect will use
        status code 301. If ``False``, then the redirect will use status code
        302. By default, ``permanent`` is ``True``.

    .. attribute:: query_string

        Whether to pass along the GET query string to the new location. If
        ``True``, then the query string is appended to the URL. If ``False``,
        then the query string is discarded. By default, ``query_string`` is
        ``False``.

    .. method:: get_redirect_url(**kwargs)

        Constructs the target URL for redirection.

        The default implementation uses :attr:`~RedirectView.url` as a starting
        string, performs expansion of ``%`` parameters in that string, as well
        as the appending of query string if requested by
        :attr:`~RedirectView.query_string`. Subclasses may implement any
        behavior they wish, as long as the method returns a redirect-ready URL
        string.

Detail views
------------

.. currentmodule:: django.views.generic.detail

DetailView
~~~~~~~~~~
.. class:: BaseDetailView()
.. class:: DetailView()

    A page representing an individual object.

    While this view is executing, ``self.object`` will contain the object that
    the view is operating upon.

    :class:`~django.views.generic.base.BaseDetailView` implements the same
    behavior as :class:`~django.views.generic.base.DetailView`, but doesn't
    include the
    :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`.

    **Mixins**

      * :class:`django.views.generic.detail.SingleObjectMixin`
      * :class:`django.views.generic.detail.SingleObjectTemplateResponseMixin`

List views
----------

.. currentmodule:: django.views.generic.list

ListView
~~~~~~~~
.. class:: BaseListView()
.. class:: ListView()

    A page representing a list of objects.

    While this view is executing, ``self.object_list`` will contain the list of
    objects (usually, but not necessarily a queryset) that the view is
    operating upon.

    :class:`~django.views.generic.list.BaseListView` implements the same
    behavior as :class:`~django.views.generic.list.ListView`, but doesn't
    include the
    :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`.

    **Mixins**

      * :class:`django.views.generic.list.MultipleObjectMixin`
      * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`


Editing views
-------------

.. currentmodule:: django.views.generic.edit

FormView
~~~~~~~~
.. class:: BaseFormView()
.. class:: FormView()

    A view that displays a form. On error, redisplays the form with validation
    errors; on success, redirects to a new URL.

    :class:`~django.views.generic.edit.BaseFormView` implements the same
    behavior as :class:`~django.views.generic.edit.FormView`, but doesn't
    include the :class:`~django.views.generic.base.TemplateResponseMixin`.

    **Mixins**

      * :class:`django.views.generic.edit.FormMixin`
      * :class:`django.views.generic.edit.ProcessFormView`

CreateView
~~~~~~~~~~
.. class:: BaseCreateView()
.. class:: CreateView()

    A view that displays a form for creating an object, redisplaying the form
    with validation errors (if there are any) and saving the object.

    :class:`~django.views.generic.edit.BaseCreateView` implements the same
    behavior as :class:`~django.views.generic.edit.CreateView`, but doesn't
    include the :class:`~django.views.generic.base.TemplateResponseMixin`.

    **Mixins**

      * :class:`django.views.generic.edit.ModelFormMixin`
      * :class:`django.views.generic.edit.ProcessFormView`

UpdateView
~~~~~~~~~~
.. class:: BaseUpdateView()
.. class:: UpdateView()

    A view that displays a form for editing an existing object, redisplaying
    the form with validation errors (if there are any) and saving changes to
    the object. This uses a form automatically generated from the object's
    model class (unless a form class is manually specified).

    :class:`~django.views.generic.edit.BaseUpdateView` implements the same
    behavior as :class:`~django.views.generic.edit.UpdateView`, but doesn't
    include the :class:`~django.views.generic.base.TemplateResponseMixin`.

    **Mixins**

      * :class:`django.views.generic.edit.ModelFormMixin`
      * :class:`django.views.generic.edit.ProcessFormView`

DeleteView
~~~~~~~~~~
.. class:: BaseDeleteView()
.. class:: DeleteView()

    A view that displays a confirmation page and deletes an existing object.
    The given object will only be deleted if the request method is ``POST``. If
    this view is fetched via ``GET``, it will display a confirmation page that
    should contain a form that POSTs to the same URL.

    :class:`~django.views.generic.edit.BaseDeleteView` implements the same
    behavior as :class:`~django.views.generic.edit.DeleteView`, but doesn't
    include the :class:`~django.views.generic.base.TemplateResponseMixin`.

    **Mixins**

      * :class:`django.views.generic.edit.ModelFormMixin`
      * :class:`django.views.generic.edit.ProcessFormView`

    **Notes**

       * The delete confirmation page displayed to a GET request uses a
         ``template_name_suffix`` of ``'_confirm_delete'``.

Date-based views
----------------

Date-based generic views (in the module :mod:`django.views.generic.dates`)
are views for displaying drilldown pages for date-based data.

.. currentmodule:: django.views.generic.dates

ArchiveIndexView
~~~~~~~~~~~~~~~~
.. class:: BaseArchiveIndexView()
.. class:: ArchiveIndexView()

    A top-level index page showing the "latest" objects, by date. Objects with
    a date in the *future* are not included unless you set ``allow_future`` to
    ``True``.

    :class:`~django.views.generic.dates.BaseArchiveIndexView` implements the
    same behavior as :class:`~django.views.generic.dates.ArchiveIndexView`, but
    doesn't include the
    :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`.

    **Mixins**

        * :class:`django.views.generic.dates.BaseDateListView`
        * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`

    **Notes**

        * Uses a default ``context_object_name`` of ``latest``.
        * Uses a default ``template_name_suffix`` of ``_archive``.

YearArchiveView
~~~~~~~~~~~~~~~
.. class:: BaseYearArchiveView()
.. class:: YearArchiveView()

    A yearly archive page showing all available months in a given year. Objects
    with a date in the *future* are not displayed unless you set
    ``allow_future`` to ``True``.

    :class:`~django.views.generic.dates.BaseYearArchiveView` implements the
    same behavior as :class:`~django.views.generic.dates.YearArchiveView`, but
    doesn't include the
    :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`.

    **Mixins**

        * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
        * :class:`django.views.generic.dates.YearMixin`
        * :class:`django.views.generic.dates.BaseDateListView`

    .. attribute:: make_object_list

        A boolean specifying whether to retrieve the full list of objects for
        this year and pass those to the template. If ``True``, the list of
        objects will be made available to the context. By default, this is
        ``False``.

    .. method:: get_make_object_list()

        Determine if an object list will be returned as part of the context. If
        ``False``, the ``None`` queryset will be used as the object list.

    **Context**

    In addition to the context provided by
    :class:`django.views.generic.list.MultipleObjectMixin` (via
    :class:`django.views.generic.dates.BaseDateListView`), the template's
    context will be:

        * ``date_list``: A ``DateQuerySet`` object containing all months that
          have objects available according to ``queryset``, represented as
          ``datetime.datetime`` objects, in ascending order.

        * ``year``: The given year, as a four-character string.

    **Notes**

        * Uses a default ``template_name_suffix`` of ``_archive_year``.

MonthArchiveView
~~~~~~~~~~~~~~~~
.. class:: BaseMonthArchiveView()
.. class:: MonthArchiveView()

    A monthly archive page showing all objects in a given month. Objects with a
    date in the *future* are not displayed unless you set ``allow_future`` to
    ``True``.

    :class:`~django.views.generic.dates.BaseMonthArchiveView` implements
    the same behavior as
    :class:`~django.views.generic.dates.MonthArchiveView`, but doesn't
    include the
    :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`.

    **Mixins**

        * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
        * :class:`django.views.generic.dates.YearMixin`
        * :class:`django.views.generic.dates.MonthMixin`
        * :class:`django.views.generic.dates.BaseDateListView`

    **Context**

    In addition to the context provided by
    :class:`~django.views.generic.list.MultipleObjectMixin` (via
    :class:`~django.views.generic.dates.BaseDateListView`), the template's
    context will be:

        * ``date_list``: A ``DateQuerySet`` object containing all days that
          have objects available in the given month, according to ``queryset``,
          represented as ``datetime.datetime`` objects, in ascending order.

        * ``month``: A ``datetime.date`` object representing the given month.

        * ``next_month``: A ``datetime.date`` object representing the first day
          of the next month. If the next month is in the future, this will be
          ``None``.

        * ``previous_month``: A ``datetime.date`` object representing the first
          day of the previous month. Unlike ``next_month``, this will never be
          ``None``.

    **Notes**

        * Uses a default ``template_name_suffix`` of ``_archive_month``.

WeekArchiveView
~~~~~~~~~~~~~~~
.. class:: BaseWeekArchiveView()
.. class:: WeekArchiveView()

    A weekly archive page showing all objects in a given week. Objects with a
    date in the *future* are not displayed unless you set ``allow_future`` to
    ``True``.

    :class:`~django.views.generic.dates.BaseWeekArchiveView` implements the
    same behavior as :class:`~django.views.generic.dates.WeekArchiveView`, but
    doesn't include the
    :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`.

    **Mixins**

        * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
        * :class:`django.views.generic.dates.YearMixin`
        * :class:`django.views.generic.dates.MonthMixin`
        * :class:`django.views.generic.dates.BaseDateListView`

    **Context**

    In addition to the context provided by
    :class:`~django.views.generic.list.MultipleObjectMixin` (via
    :class:`~django.views.generic.dates.BaseDateListView`), the template's
    context will be:

        * ``week``: A ``datetime.date`` object representing the first day of
          the given week.

    **Notes**

        * Uses a default ``template_name_suffix`` of ``_archive_week``.

DayArchiveView
~~~~~~~~~~~~~~
.. class:: BaseDayArchiveView()
.. class:: DayArchiveView()

    A day archive page showing all objects in a given day. Days in the future
    throw a 404 error, regardless of whether any objects exist for future days,
    unless you set ``allow_future`` to ``True``.

    :class:`~django.views.generic.dates.BaseDayArchiveView` implements the same
    behavior as :class:`~django.views.generic.dates.DayArchiveView`, but
    doesn't include the
    :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`.

    **Mixins**

        * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
        * :class:`django.views.generic.dates.YearMixin`
        * :class:`django.views.generic.dates.MonthMixin`
        * :class:`django.views.generic.dates.DayMixin`
        * :class:`django.views.generic.dates.BaseDateListView`

    **Context**

    In addition to the context provided by
    :class:`~django.views.generic.list.MultipleObjectMixin` (via
    :class:`~django.views.generic.dates.BaseDateListView`), the template's
    context will be:

        * ``day``: A ``datetime.date`` object representing the given day.

        * ``next_day``: A ``datetime.date`` object representing the next day.
          If the next day is in the future, this will be ``None``.

        * ``previous_day``: A ``datetime.date`` object representing the
          previous day. Unlike ``next_day``, this will never be ``None``.

        * ``next_month``: A ``datetime.date`` object representing the first day
          of the next month. If the next month is in the future, this will be
          ``None``.

        * ``previous_month``: A ``datetime.date`` object representing the first
          day of the previous month. Unlike ``next_month``, this will never be
          ``None``.

    **Notes**

        * Uses a default ``template_name_suffix`` of ``_archive_day``.

TodayArchiveView
~~~~~~~~~~~~~~~~
.. class:: BaseTodayArchiveView()
.. class:: TodayArchiveView()

    A day archive page showing all objects for *today*. This is exactly the
    same as ``archive_day``, except the ``year``/``month``/``day`` arguments
    are not used,

    :class:`~django.views.generic.dates.BaseTodayArchiveView` implements the
    same behavior as :class:`~django.views.generic.dates.TodayArchiveView`, but
    doesn't include the
    :class:`~django.views.generic.list.MultipleObjectTemplateResponseMixin`.

    **Mixins**

        * :class:`django.views.generic.dates.DayArchiveView`

DateDetailView
~~~~~~~~~~~~~~
.. class:: BaseDateDetailView()
.. class:: DateDetailView()

    A page representing an individual object. If the object has a date value in
    the future, the view will throw a 404 error by default, unless you set
    ``allow_future`` to ``True``.

    :class:`~django.views.generic.dates.BaseDateDetailView` implements the same
    behavior as :class:`~django.views.generic.dates.DateDetailView`, but
    doesn't include the
    :class:`~django.views.generic.detail.SingleObjectTemplateResponseMixin`.

    **Mixins**

        * :class:`django.views.generic.list.MultipleObjectTemplateResponseMixin`
        * :class:`django.views.generic.dates.YearMixin`
        * :class:`django.views.generic.dates.MonthMixin`
        * :class:`django.views.generic.dates.DayMixin`
        * :class:`django.views.generic.dates.BaseDateListView`