Arthur de Jong

Open Source / Free Software developer

summaryrefslogtreecommitdiffstats
path: root/docs/ref/utils.txt
blob: f5b2331cad0b779f29aeb464e2025a4c526e72f0 (plain)
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
============
Django Utils
============

.. module:: django.utils
   :synopsis: Django's built-in utilities.

This document covers all stable modules in ``django.utils``. Most of the
modules in ``django.utils`` are designed for internal use and only the
following parts can be considered stable and thus backwards compatible as per
the :ref:`internal release deprecation policy <internal-release-deprecation-policy>`.

``django.utils.cache``
======================

.. module:: django.utils.cache
   :synopsis: Helper functions for controlling caching.

This module contains helper functions for controlling caching. It does so by
managing the ``Vary`` header of responses. It includes functions to patch the
header of response objects directly and decorators that change functions to do
that header-patching themselves.

For information on the ``Vary`` header, see :rfc:`2616#section-14.44` section
14.44.

Essentially, the ``Vary`` HTTP header defines which headers a cache should take
into account when building its cache key. Requests with the same path but
different header content for headers named in ``Vary`` need to get different
cache keys to prevent delivery of wrong content.

For example, :doc:`internationalization </topics/i18n/index>` middleware would
need to distinguish caches by the ``Accept-language`` header.

.. function:: patch_cache_control(response, **kwargs)

    This function patches the ``Cache-Control`` header by adding all keyword
    arguments to it. The transformation is as follows:

    * All keyword parameter names are turned to lowercase, and underscores
      are converted to hyphens.
    * If the value of a parameter is ``True`` (exactly ``True``, not just a
      true value), only the parameter name is added to the header.
    * All other parameters are added with their value, after applying
      ``str()`` to it.

.. function:: get_max_age(response)

    Returns the max-age from the response Cache-Control header as an integer
    (or ``None`` if it wasn't found or wasn't an integer).

.. function:: patch_response_headers(response, cache_timeout=None)

    Adds some useful headers to the given ``HttpResponse`` object:

    * ``ETag``
    * ``Last-Modified``
    * ``Expires``
    * ``Cache-Control``

    Each header is only added if it isn't already set.

    ``cache_timeout`` is in seconds. The :setting:`CACHE_MIDDLEWARE_SECONDS`
    setting is used by default.

.. function:: add_never_cache_headers(response)

    Adds a ``Cache-Control: max-age=0, no-cache, no-store, must-revalidate``
    header to a response to indicate that a page should never be cached.

    .. versionchanged:: 1.9

        Before Django 1.9, ``Cache-Control: max-age=0`` was sent. This didn't
        reliably prevent caching in all browsers.

.. function:: patch_vary_headers(response, newheaders)

    Adds (or updates) the ``Vary`` header in the given ``HttpResponse`` object.
    ``newheaders`` is a list of header names that should be in ``Vary``.
    Existing headers in ``Vary`` aren't removed.

.. function:: get_cache_key(request, key_prefix=None)

    Returns a cache key based on the request path. It can be used in the
    request phase because it pulls the list of headers to take into account
    from the global path registry and uses those to build a cache key to
    check against.

    If there is no headerlist stored, the page needs to be rebuilt, so this
    function returns ``None``.

.. function:: learn_cache_key(request, response, cache_timeout=None, key_prefix=None)

    Learns what headers to take into account for some request path from the
    response object. It stores those headers in a global path registry so that
    later access to that path will know what headers to take into account
    without building the response object itself. The headers are named in
    the ``Vary`` header of the response, but we want to prevent response
    generation.

    The list of headers to use for cache key generation is stored in the same
    cache as the pages themselves. If the cache ages some data out of the
    cache, this just means that we have to build the response once to get at
    the Vary header and so at the list of headers to use for the cache key.

``django.utils.dateparse``
==========================

.. module:: django.utils.dateparse
   :synopsis: Functions to parse datetime objects.

The functions defined in this module share the following properties:

- They raise :exc:`ValueError` if their input is well formatted but isn't a
  valid date or time.
- They return ``None`` if it isn't well formatted at all.
- They accept up to picosecond resolution in input, but they truncate it to
  microseconds, since that's what Python supports.

.. function:: parse_date(value)

    Parses a string and returns a :class:`datetime.date`.

.. function:: parse_time(value)

    Parses a string and returns a :class:`datetime.time`.

    UTC offsets aren't supported; if ``value`` describes one, the result is
    ``None``.

.. function:: parse_datetime(value)

    Parses a string and returns a :class:`datetime.datetime`.

    UTC offsets are supported; if ``value`` describes one, the result's
    ``tzinfo`` attribute is a :class:`~django.utils.timezone.FixedOffset`
    instance.

.. function:: parse_duration(value)

    Parses a string and returns a :class:`datetime.timedelta`.

    Expects data in the format ``"DD HH:MM:SS.uuuuuu"`` or as specified by ISO
    8601 (e.g. ``P4DT1H15M20S`` which is equivalent to ``4 1:15:20``).

``django.utils.decorators``
===========================

.. module:: django.utils.decorators
    :synopsis: Functions that help with creating decorators for views.

.. function:: method_decorator(decorator, name='')

    Converts a function decorator into a method decorator. It can be used to
    decorate methods or classes; in the latter case, ``name`` is the name
    of the method to be decorated and is required.

    ``decorator`` may also be a a list or tuple of functions. They are wrapped
    in reverse order so that the call order is the order in which the functions
    appear in the list/tuple.

    See :ref:`decorating class based views <decorating-class-based-views>` for
    example usage.

    .. versionchanged:: 1.9

       The ability to decorate classes, the ``name`` parameter, and the ability
       for ``decorator`` to accept a list/tuple of decorator functions were
       added.

.. function:: decorator_from_middleware(middleware_class)

    Given a middleware class, returns a view decorator. This lets you use
    middleware functionality on a per-view basis. The middleware is created
    with no params passed.

.. function:: decorator_from_middleware_with_args(middleware_class)

    Like ``decorator_from_middleware``, but returns a function
    that accepts the arguments to be passed to the middleware_class.
    For example, the :func:`~django.views.decorators.cache.cache_page`
    decorator is created from the ``CacheMiddleware`` like this::

         cache_page = decorator_from_middleware_with_args(CacheMiddleware)

         @cache_page(3600)
         def my_view(request):
             pass

``django.utils.encoding``
=========================

.. module:: django.utils.encoding
   :synopsis: A series of helper functions to manage character encoding.

.. function:: python_2_unicode_compatible

    A decorator that defines ``__unicode__`` and ``__str__`` methods under
    Python 2. Under Python 3 it does nothing.

    To support Python 2 and 3 with a single code base, define a ``__str__``
    method returning text and apply this decorator to the class.

.. function:: smart_text(s, encoding='utf-8', strings_only=False, errors='strict')

    Returns a text object representing ``s`` -- ``unicode`` on Python 2 and
    ``str`` on Python 3. Treats bytestrings using the ``encoding`` codec.

    If ``strings_only`` is ``True``, don't convert (some) non-string-like
    objects.

.. function:: smart_unicode(s, encoding='utf-8', strings_only=False, errors='strict')

    Historical name of :func:`smart_text`. Only available under Python 2.

.. function:: is_protected_type(obj)

    Determine if the object instance is of a protected type.

    Objects of protected types are preserved as-is when passed to
    ``force_text(strings_only=True)``.

.. function:: force_text(s, encoding='utf-8', strings_only=False, errors='strict')

    Similar to ``smart_text``, except that lazy instances are resolved to
    strings, rather than kept as lazy objects.

    If ``strings_only`` is ``True``, don't convert (some) non-string-like
    objects.

.. function:: force_unicode(s, encoding='utf-8', strings_only=False, errors='strict')

    Historical name of :func:`force_text`. Only available under Python 2.

.. function:: smart_bytes(s, encoding='utf-8', strings_only=False, errors='strict')

    Returns a bytestring version of ``s``, encoded as specified in
    ``encoding``.

    If ``strings_only`` is ``True``, don't convert (some) non-string-like
    objects.

.. function:: force_bytes(s, encoding='utf-8', strings_only=False, errors='strict')

    Similar to ``smart_bytes``, except that lazy instances are resolved to
    bytestrings, rather than kept as lazy objects.

    If ``strings_only`` is ``True``, don't convert (some) non-string-like
    objects.

.. function:: smart_str(s, encoding='utf-8', strings_only=False, errors='strict')

    Alias of :func:`smart_bytes` on Python 2 and :func:`smart_text` on Python
    3. This function returns a ``str`` or a lazy string.

    For instance, this is  suitable for writing to :data:`sys.stdout` on
    Python 2 and 3.

.. function:: force_str(s, encoding='utf-8', strings_only=False, errors='strict')

    Alias of :func:`force_bytes` on Python 2 and :func:`force_text` on Python
    3. This function always returns a ``str``.

.. function:: iri_to_uri(iri)

    Convert an Internationalized Resource Identifier (IRI) portion to a URI
    portion that is suitable for inclusion in a URL.

    This is the algorithm from section 3.1 of :rfc:`3987#section-3.1`. However,
    since we are assuming input is either UTF-8 or unicode already, we can
    simplify things a little from the full method.

    Takes an IRI in UTF-8 bytes and returns ASCII bytes containing the encoded
    result.

.. function:: uri_to_iri(uri)

    Converts a Uniform Resource Identifier into an Internationalized Resource
    Identifier.

    This is an algorithm from section 3.2 of :rfc:`3987#section-3.2`.

    Takes a URI in ASCII bytes and returns a unicode string containing the
    encoded result.

.. function:: filepath_to_uri(path)

    Convert a file system path to a URI portion that is suitable for inclusion
    in a URL. The path is assumed to be either UTF-8 or unicode.

    This method will encode certain characters that would normally be
    recognized as special characters for URIs.  Note that this method does not
    encode the ' character, as it is a valid character within URIs. See
    ``encodeURIComponent()`` JavaScript function for more details.

    Returns an ASCII string containing the encoded result.

.. function:: escape_uri_path(path)

    Escapes the unsafe characters from the path portion of a Uniform Resource
    Identifier (URI).

``django.utils.feedgenerator``
==============================

.. module:: django.utils.feedgenerator
   :synopsis: Syndication feed generation library -- used for generating RSS, etc.

Sample usage::

    >>> from django.utils import feedgenerator
    >>> feed = feedgenerator.Rss201rev2Feed(
    ...     title="Poynter E-Media Tidbits",
    ...     link="http://www.poynter.org/column.asp?id=31",
    ...     description="A group Weblog by the sharpest minds in online media/journalism/publishing.",
    ...     language="en",
    ... )
    >>> feed.add_item(
    ...     title="Hello",
    ...     link="http://www.holovaty.com/test/",
    ...     description="Testing."
    ... )
    >>> with open('test.rss', 'w') as fp:
    ...     feed.write(fp, 'utf-8')

For simplifying the selection of a generator use ``feedgenerator.DefaultFeed``
which is currently ``Rss201rev2Feed``

For definitions of the different versions of RSS, see:
http://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss

.. function:: get_tag_uri(url, date)

    Creates a TagURI.

    See http://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id

SyndicationFeed
---------------

.. class:: SyndicationFeed

    Base class for all syndication feeds. Subclasses should provide write().

    .. method:: __init__(title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, **kwargs)

        Initialize the feed with the given dictionary of metadata, which applies
        to the entire feed.

        Any extra keyword arguments you pass to ``__init__`` will be stored in
        ``self.feed``.

        All parameters should be Unicode objects, except ``categories``, which
        should be a sequence of Unicode objects.

    .. method:: add_item(title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, enclosure=None, categories=(), item_copyright=None, ttl=None, updateddate=None, enclosures=None, **kwargs)

        Adds an item to the feed. All args are expected to be Python ``unicode``
        objects except ``pubdate`` and ``updateddate``, which are ``datetime.datetime``
        objects, ``enclosure``, which is an ``Enclosure`` instance, and
        ``enclosures``, which is a list of ``Enclosure`` instances.

        .. deprecated:: 1.9

            The ``enclosure`` keyword argument is deprecated in favor of the
            new ``enclosures`` keyword argument which accepts a list of
            ``Enclosure`` objects.

    .. method:: num_items()

    .. method:: root_attributes()

        Return extra attributes to place on the root (i.e. feed/channel)
        element. Called from ``write()``.

    .. method:: add_root_elements(handler)

        Add elements in the root (i.e. feed/channel) element.
        Called from ``write()``.

    .. method:: item_attributes(item)

        Return extra attributes to place on each item (i.e. item/entry)
        element.

    .. method:: add_item_elements(handler, item)

        Add elements on each item (i.e. item/entry) element.

    .. method:: write(outfile, encoding)

        Outputs the feed in the given encoding to ``outfile``, which is a
        file-like object. Subclasses should override this.

    .. method:: writeString(encoding)

        Returns the feed in the given encoding as a string.

    .. method:: latest_post_date()

        Returns the latest ``pubdate`` or ``updateddate`` for all items in the
        feed. If no items have either of these attributes this returns the
        current date/time.

Enclosure
---------

.. class:: Enclosure

    Represents an RSS enclosure

RssFeed
-------

.. class:: RssFeed(SyndicationFeed)

Rss201rev2Feed
--------------

.. class:: Rss201rev2Feed(RssFeed)

    Spec: http://cyber.law.harvard.edu/rss/rss.html

RssUserland091Feed
------------------

.. class:: RssUserland091Feed(RssFeed)

    Spec: http://backend.userland.com/rss091

Atom1Feed
---------

.. class:: Atom1Feed(SyndicationFeed)

    Spec: http://tools.ietf.org/html/rfc4287

``django.utils.functional``
===========================

.. module:: django.utils.functional
    :synopsis: Functional programming tools.

.. class:: cached_property(object, name)

    The ``@cached_property`` decorator caches the result of a method with a
    single ``self`` argument as a property. The cached result will persist
    as long as the instance does, so if the instance is passed around and the
    function subsequently invoked, the cached result will be returned.

    Consider a typical case, where a view might need to call a model's method
    to perform some computation, before placing the model instance into the
    context, where the template might invoke the method once more::

        # the model
        class Person(models.Model):

            def friends(self):
                # expensive computation
                ...
                return friends

        # in the view:
        if person.friends():
            ...

    And in the template you would have:

    .. code-block:: html+django

        {% for friend in person.friends %}

    Here, ``friends()`` will be called twice. Since the instance ``person`` in
    the view and the template are the same, ``@cached_property`` can avoid
    that::

        from django.utils.functional import cached_property

        @cached_property
        def friends(self):
            # expensive computation
            ...
            return friends

    Note that as the method is now a property, in Python code it will need to
    be invoked appropriately::

        # in the view:
        if person.friends:
            ...

    The cached value can be treated like an ordinary attribute of the instance::

        # clear it, requiring re-computation next time it's called
        del person.friends # or delattr(person, "friends")

        # set a value manually, that will persist on the instance until cleared
        person.friends = ["Huckleberry Finn", "Tom Sawyer"]

    As well as offering potential performance advantages, ``@cached_property``
    can ensure that an attribute's value does not change unexpectedly over the
    life of an instance. This could occur with a method whose computation is
    based on ``datetime.now()``, or simply if a change were saved to the
    database by some other process in the brief interval between subsequent
    invocations of a method on the same instance.

    You can use the ``name`` argument to make cached properties of other
    methods. For example, if you had an expensive ``get_friends()`` method and
    wanted to allow calling it without retrieving the cached value, you could
    write::

        friends = cached_property(get_friends, name='friends')

    While ``person.get_friends()`` will recompute the friends on each call, the
    value of the cached property will persist until you delete it as described
    above::

        x = person.friends         # calls first time
        y = person.get_friends()   # calls again
        z = person.friends         # does not call
        x is z                     # is True

.. function:: allow_lazy(func, *resultclasses)

    Django offers many utility functions (particularly in ``django.utils``)
    that take a string as their first argument and do something to that string.
    These functions are used by template filters as well as directly in other
    code.

    If you write your own similar functions and deal with translations, you'll
    face the problem of what to do when the first argument is a lazy
    translation object. You don't want to convert it to a string immediately,
    because you might be using this function outside of a view (and hence the
    current thread's locale setting will not be correct).

    For cases like this, use the ``django.utils.functional.allow_lazy()``
    decorator. It modifies the function so that *if* it's called with a lazy
    translation as one of its arguments, the function evaluation is delayed
    until it needs to be converted to a string.

    For example::

        from django.utils.functional import allow_lazy

        def fancy_utility_function(s, ...):
            # Do some conversion on string 's'
            ...
        # Replace unicode by str on Python 3
        fancy_utility_function = allow_lazy(fancy_utility_function, unicode)

    The ``allow_lazy()`` decorator takes, in addition to the function to
    decorate, a number of extra arguments (``*args``) specifying the type(s)
    that the original function can return. Usually, it's enough to include
    ``unicode`` (or ``str`` on Python 3) here and ensure that your function
    returns only Unicode strings.

    Using this decorator means you can write your function and assume that the
    input is a proper string, then add support for lazy translation objects at
    the end.

``django.utils.html``
=====================

.. module:: django.utils.html
   :synopsis: HTML helper functions

Usually you should build up HTML using Django's templates to make use of its
autoescape mechanism, using the utilities in :mod:`django.utils.safestring`
where appropriate. This module provides some additional low level utilities for
escaping HTML.

.. function:: escape(text)

    Returns the given text with ampersands, quotes and angle brackets encoded
    for use in HTML. The input is first passed through
    :func:`~django.utils.encoding.force_text` and the output has
    :func:`~django.utils.safestring.mark_safe` applied.

.. function:: conditional_escape(text)

    Similar to ``escape()``, except that it doesn't operate on pre-escaped
    strings, so it will not double escape.

.. function:: format_html(format_string, *args, **kwargs)

    This is similar to `str.format`_, except that it is appropriate for
    building up HTML fragments. All args and kwargs are passed through
    :func:`conditional_escape` before being passed to ``str.format``.

    For the case of building up small HTML fragments, this function is to be
    preferred over string interpolation using ``%`` or ``str.format`` directly,
    because it applies escaping to all arguments - just like the Template system
    applies escaping by default.

    So, instead of writing::

        mark_safe("%s <b>%s</b> %s" % (some_html,
                                        escape(some_text),
                                        escape(some_other_text),
                                        ))

    You should instead use::

        format_html("{} <b>{}</b> {}",
                    mark_safe(some_html), some_text, some_other_text)

    This has the advantage that you don't need to apply :func:`escape` to each
    argument and risk a bug and an XSS vulnerability if you forget one.

    Note that although this function uses ``str.format`` to do the
    interpolation, some of the formatting options provided by `str.format`_
    (e.g. number formatting) will not work, since all arguments are passed
    through :func:`conditional_escape` which (ultimately) calls
    :func:`~django.utils.encoding.force_text` on the values.

    .. _str.format: https://docs.python.org/library/stdtypes.html#str.format

.. function:: format_html_join(sep, format_string, args_generator)

    A wrapper of :func:`format_html`, for the common case of a group of
    arguments that need to be formatted using the same format string, and then
    joined using ``sep``. ``sep`` is also passed through
    :func:`conditional_escape`.

    ``args_generator`` should be an iterator that returns the sequence of
    ``args`` that will be passed to :func:`format_html`. For example::

        format_html_join('\n', "<li>{} {}</li>", ((u.first_name, u.last_name)
                                                    for u in users))

.. function:: strip_tags(value)

    Tries to remove anything that looks like an HTML tag from the string, that
    is anything contained within ``<>``.

    Absolutely NO guarantee is provided about the resulting string being
    HTML safe. So NEVER mark safe the result of a ``strip_tag`` call without
    escaping it first, for example with :func:`~django.utils.html.escape`.

    For example::

        strip_tags(value)

    If ``value`` is ``"<b>Joel</b> <button>is</button> a <span>slug</span>"``
    the return value will be ``"Joel is a slug"``.

    If you are looking for a more robust solution, take a look at the `bleach
    <https://pypi.python.org/pypi/bleach>`_ Python library.

.. function:: html_safe()

    The ``__html__()`` method on a class helps non-Django templates detect
    classes whose output doesn't require HTML escaping.

    This decorator defines the ``__html__()`` method on the decorated class
    by wrapping the ``__unicode__()`` (Python 2) or ``__str__()`` (Python 3)
    in :meth:`~django.utils.safestring.mark_safe`. Ensure the ``__unicode__()``
    or ``__str__()`` method does indeed return text that doesn't require HTML
    escaping.


``django.utils.http``
=====================

.. module:: django.utils.http
   :synopsis: HTTP helper functions. (URL encoding, cookie handling, ...)

.. function:: urlquote(url, safe='/')

    A version of Python's ``urllib.quote()`` function that can operate on
    unicode strings. The url is first UTF-8 encoded before quoting. The
    returned string can safely be used as part of an argument to a subsequent
    ``iri_to_uri()`` call without double-quoting occurring. Employs lazy
    execution.

.. function:: urlquote_plus(url, safe='')

    A version of Python's urllib.quote_plus() function that can operate on
    unicode strings. The url is first UTF-8 encoded before quoting. The
    returned string can safely be used as part of an argument to a subsequent
    ``iri_to_uri()`` call without double-quoting occurring. Employs lazy
    execution.

.. function:: urlencode(query, doseq=0)

    A version of Python's urllib.urlencode() function that can operate on
    unicode strings. The parameters are first cast to UTF-8 encoded strings
    and then encoded as per normal.

.. function:: cookie_date(epoch_seconds=None)

    Formats the time to ensure compatibility with Netscape's cookie standard.

    Accepts a floating point number expressed in seconds since the epoch in
    UTC--such as that outputted by ``time.time()``. If set to ``None``,
    defaults to the current time.

    Outputs a string in the format ``Wdy, DD-Mon-YYYY HH:MM:SS GMT``.

.. function:: http_date(epoch_seconds=None)

    Formats the time to match the :rfc:`1123` date format as specified by HTTP
    :rfc:`2616#section-3.3.1` section 3.3.1.

    Accepts a floating point number expressed in seconds since the epoch in
    UTC--such as that outputted by ``time.time()``. If set to ``None``,
    defaults to the current time.

    Outputs a string in the format ``Wdy, DD Mon YYYY HH:MM:SS GMT``.

.. function:: base36_to_int(s)

    Converts a base 36 string to an integer. On Python 2 the output is
    guaranteed to be an ``int`` and not a ``long``.

.. function:: int_to_base36(i)

    Converts a positive integer to a base 36 string. On Python 2 ``i`` must be
    smaller than `sys.maxint`_.

    .. _sys.maxint: https://docs.python.org/2/library/sys.html#sys.maxint

.. function:: urlsafe_base64_encode(s)

    Encodes a bytestring in base64 for use in URLs, stripping any trailing
    equal signs.

.. function::  urlsafe_base64_decode(s)

    Decodes a base64 encoded string, adding back any trailing equal signs that
    might have been stripped.

``django.utils.module_loading``
===============================

.. module:: django.utils.module_loading
   :synopsis: Functions for working with Python modules.

Functions for working with Python modules.

.. function:: import_string(dotted_path)

    Imports a dotted module path and returns the attribute/class designated by
    the last name in the path. Raises ``ImportError`` if the import failed. For
    example::

        from django.utils.module_loading import import_string
        ValidationError = import_string('django.core.exceptions.ValidationError')

    is equivalent to::

        from django.core.exceptions import ValidationError

``django.utils.safestring``
===========================

.. module:: django.utils.safestring
   :synopsis: Functions and classes for working with strings that can be displayed safely without further escaping in HTML.

Functions and classes for working with "safe strings": strings that can be
displayed safely without further escaping in HTML. Marking something as a "safe
string" means that the producer of the string has already turned characters
that should not be interpreted by the HTML engine (e.g. '<') into the
appropriate entities.

.. class:: SafeBytes

    A ``bytes`` subclass that has been specifically marked as "safe"
    (requires no further escaping) for HTML output purposes.

.. class:: SafeString

    A ``str`` subclass that has been specifically marked as "safe"
    (requires no further escaping) for HTML output purposes. This is
    :class:`SafeBytes` on Python 2 and :class:`SafeText` on Python 3.

.. class:: SafeText

    A ``str`` (in Python 3) or ``unicode`` (in Python 2) subclass
    that has been specifically marked as "safe" for HTML output purposes.

.. class:: SafeUnicode

    Historical name of :class:`SafeText`. Only available under Python 2.

.. function:: mark_safe(s)

    Explicitly mark a string as safe for (HTML) output purposes. The returned
    object can be used everywhere a string or unicode object is appropriate.

    Can be called multiple times on a single string.

    For building up fragments of HTML, you should normally be using
    :func:`django.utils.html.format_html` instead.

    String marked safe will become unsafe again if modified. For example::

        >>> mystr = '<b>Hello World</b>   '
        >>> mystr = mark_safe(mystr)
        >>> type(mystr)
        <class 'django.utils.safestring.SafeBytes'>

        >>> mystr = mystr.strip()  # removing whitespace
        >>> type(mystr)
        <type 'str'>

.. function:: mark_for_escaping(s)

    Explicitly mark a string as requiring HTML escaping upon output. Has no
    effect on ``SafeData`` subclasses.

    Can be called multiple times on a single string (the resulting escaping is
    only applied once).

``django.utils.text``
=====================

.. module:: django.utils.text
    :synopsis: Text manipulation.

.. function:: slugify(allow_unicode=False)

    Converts to ASCII if ``allow_unicode`` is ``False`` (default). Converts spaces to
    hyphens. Removes characters that aren't alphanumerics, underscores, or
    hyphens. Converts to lowercase. Also strips leading and trailing whitespace.

    For example::

        slugify(value)

    If ``value`` is ``"Joel is a slug"``, the output will be
    ``"joel-is-a-slug"``.

    You can set the ``allow_unicode`` parameter to ``True``, if you want to
    allow Unicode characters::

        slugify(value, allow_unicode=True)

    If ``value`` is ``"你好 World"``, the output will be ``"你好-world"``.

    .. versionchanged:: 1.9

        The ``allow_unicode`` parameter was added.

.. _time-zone-selection-functions:

``django.utils.timezone``
=========================

.. module:: django.utils.timezone
    :synopsis: Timezone support.

.. data:: utc

    :class:`~datetime.tzinfo` instance that represents UTC.

.. class:: FixedOffset(offset=None, name=None)

    A :class:`~datetime.tzinfo` subclass modeling a fixed offset from UTC.
    ``offset`` is an integer number of minutes east of UTC.

.. function:: get_fixed_timezone(offset)

    Returns a :class:`~datetime.tzinfo` instance that represents a time zone
    with a fixed offset from UTC.

    ``offset`` is a :class:`datetime.timedelta` or an integer number of
    minutes. Use positive values for time zones east of UTC and negative
    values for west of UTC.

.. function:: get_default_timezone()

    Returns a :class:`~datetime.tzinfo` instance that represents the
    :ref:`default time zone <default-current-time-zone>`.

.. function:: get_default_timezone_name()

    Returns the name of the :ref:`default time zone
    <default-current-time-zone>`.

.. function:: get_current_timezone()

    Returns a :class:`~datetime.tzinfo` instance that represents the
    :ref:`current time zone <default-current-time-zone>`.

.. function:: get_current_timezone_name()

    Returns the name of the :ref:`current time zone
    <default-current-time-zone>`.

.. function:: activate(timezone)

    Sets the :ref:`current time zone <default-current-time-zone>`. The
    ``timezone`` argument must be an instance of a :class:`~datetime.tzinfo`
    subclass or, if pytz_ is available, a time zone name.

.. function:: deactivate()

    Unsets the :ref:`current time zone <default-current-time-zone>`.

.. function:: override(timezone)

    This is a Python context manager that sets the :ref:`current time zone
    <default-current-time-zone>` on entry with :func:`activate()`, and restores
    the previously active time zone on exit. If the ``timezone`` argument is
    ``None``, the :ref:`current time zone <default-current-time-zone>` is unset
    on entry with :func:`deactivate()` instead.

    ``override`` is also usable as a function decorator.

.. function:: localtime(value, timezone=None)

    Converts an aware :class:`~datetime.datetime` to a different time zone,
    by default the :ref:`current time zone <default-current-time-zone>`.

    This function doesn't work on naive datetimes; use :func:`make_aware`
    instead.

.. function:: now()

    Returns a :class:`~datetime.datetime` that represents the
    current point in time. Exactly what's returned depends on the value of
    :setting:`USE_TZ`:

    * If :setting:`USE_TZ` is ``False``, this will be a
      :ref:`naive <naive_vs_aware_datetimes>` datetime (i.e. a datetime
      without an associated timezone) that represents the current time
      in the system's local timezone.

    * If :setting:`USE_TZ` is ``True``, this will be an
      :ref:`aware <naive_vs_aware_datetimes>` datetime representing the
      current time in UTC. Note that :func:`now` will always return
      times in UTC regardless of the value of :setting:`TIME_ZONE`;
      you can use :func:`localtime` to convert to a time in the current
      time zone.

.. function:: is_aware(value)

    Returns ``True`` if ``value`` is aware, ``False`` if it is naive. This
    function assumes that ``value`` is a :class:`~datetime.datetime`.

.. function:: is_naive(value)

    Returns ``True`` if ``value`` is naive, ``False`` if it is aware. This
    function assumes that ``value`` is a :class:`~datetime.datetime`.

.. function:: make_aware(value, timezone=None, is_dst=None)

    Returns an aware :class:`~datetime.datetime` that represents the same
    point in time as ``value`` in ``timezone``, ``value`` being a naive
    :class:`~datetime.datetime`. If ``timezone`` is set to ``None``, it
    defaults to the :ref:`current time zone <default-current-time-zone>`.

    When pytz_ is installed, the exception ``pytz.AmbiguousTimeError``
    will be raised if you try to make ``value`` aware during a DST transition
    where the same time occurs twice (when reverting from DST). Setting
    ``is_dst`` to ``True`` or ``False`` will avoid the exception by choosing if
    the time is pre-transition or post-transition respectively.

    When pytz_ is installed, the exception ``pytz.NonExistentTimeError``
    will be raised if you try to make ``value`` aware during a DST transition
    such that the time never occurred (when entering into DST). Setting
    ``is_dst`` to ``True`` or ``False`` will avoid the exception by moving the
    hour backwards or forwards by 1 respectively. For example, ``is_dst=True``
    would change a non-existent time of 2:30 to 1:30 and ``is_dst=False``
    would change the time to 3:30.

    ``is_dst`` has no effect when ``pytz`` is not installed.

    .. versionchanged:: 1.9

        The ``is_dst`` argument was added.

.. function:: make_naive(value, timezone=None)

    Returns an naive :class:`~datetime.datetime` that represents in
    ``timezone``  the same point in time as ``value``, ``value`` being an
    aware :class:`~datetime.datetime`. If ``timezone`` is set to ``None``, it
    defaults to the :ref:`current time zone <default-current-time-zone>`.

.. _pytz: http://pytz.sourceforge.net/

``django.utils.translation``
============================

.. module:: django.utils.translation
   :synopsis: Internationalization support.

For a complete discussion on the usage of the following see the
:doc:`translation documentation </topics/i18n/translation>`.

.. function:: gettext(message)

    Translates ``message`` and returns it in a UTF-8 bytestring

.. function:: ugettext(message)

    Translates ``message`` and returns it in a unicode string

.. function:: pgettext(context, message)

    Translates ``message`` given the ``context`` and returns
    it in a unicode string.

    For more information, see :ref:`contextual-markers`.

.. function:: gettext_lazy(message)
.. function:: ugettext_lazy(message)
.. function:: pgettext_lazy(context, message)

    Same as the non-lazy versions above, but using lazy execution.

    See :ref:`lazy translations documentation <lazy-translations>`.

.. function:: gettext_noop(message)
.. function:: ugettext_noop(message)

    Marks strings for translation but doesn't translate them now. This can be
    used to store strings in global variables that should stay in the base
    language (because they might be used externally) and will be translated
    later.

.. function:: ngettext(singular, plural, number)

    Translates ``singular`` and ``plural`` and returns the appropriate string
    based on ``number`` in a UTF-8 bytestring.

.. function:: ungettext(singular, plural, number)

    Translates ``singular`` and ``plural`` and returns the appropriate string
    based on ``number`` in a unicode string.

.. function:: npgettext(context, singular, plural, number)

    Translates ``singular`` and ``plural`` and returns the appropriate string
    based on ``number`` and the ``context`` in a unicode string.

.. function:: ngettext_lazy(singular, plural, number)
.. function:: ungettext_lazy(singular, plural, number)
.. function:: npgettext_lazy(context, singular, plural, number)

    Same as the non-lazy versions above, but using lazy execution.

    See :ref:`lazy translations documentation <lazy-translations>`.

.. function:: string_concat(*strings)

    Lazy variant of string concatenation, needed for translations that are
    constructed from multiple parts.

.. function:: activate(language)

    Fetches the translation object for a given language and activates it as
    the current translation object for the current thread.

.. function:: deactivate()

    Deactivates the currently active translation object so that further _ calls
    will resolve against the default translation object, again.

.. function:: deactivate_all()

    Makes the active translation object a ``NullTranslations()`` instance.
    This is useful when we want delayed translations to appear as the original
    string for some reason.

.. function:: override(language, deactivate=False)

    A Python context manager that uses
    :func:`django.utils.translation.activate` to fetch the translation object
    for a given language, activates it as the translation object for the
    current thread and reactivates the previous active language on exit.
    Optionally, it can simply deactivate the temporary translation on exit with
    :func:`django.utils.translation.deactivate` if the ``deactivate`` argument
    is ``True``. If you pass ``None`` as the language argument, a
    ``NullTranslations()`` instance is activated within the context.

    ``override`` is also usable as a function decorator.

.. function:: check_for_language(lang_code)

    Checks whether there is a global language file for the given language
    code (e.g. 'fr', 'pt_BR'). This is used to decide whether a user-provided
    language is available.

.. function:: get_language()

    Returns the currently selected language code. Returns ``None`` if
    translations are temporarily deactivated (by :func:`deactivate_all()` or
    when ``None`` is passed to :func:`override()`).

.. function:: get_language_bidi()

    Returns selected language's BiDi layout:

    * ``False`` = left-to-right layout
    * ``True`` = right-to-left layout

.. function:: get_language_from_request(request, check_path=False)

    Analyzes the request to find what language the user wants the system to
    show. Only languages listed in settings.LANGUAGES are taken into account.
    If the user requests a sublanguage where we have a main language, we send
    out the main language.

    If ``check_path`` is ``True``, the function first checks the requested URL
    for whether its path begins with a language code listed in the
    :setting:`LANGUAGES` setting.

.. function:: to_locale(language)

    Turns a language name (en-us) into a locale name (en_US).

.. function:: templatize(src)

    Turns a Django template into something that is understood by ``xgettext``.
    It does so by translating the Django translation tags into standard
    ``gettext`` function invocations.

.. data:: LANGUAGE_SESSION_KEY

    Session key under which the active language for the current session is
    stored.