Fixed #24493 -- Added BaseContext.setdefault()
This commit is contained in:
parent
4d9414098b
commit
388e79e9fc
|
@ -89,6 +89,13 @@ class BaseContext(object):
|
||||||
return d[key]
|
return d[key]
|
||||||
return otherwise
|
return otherwise
|
||||||
|
|
||||||
|
def setdefault(self, key, default=None):
|
||||||
|
try:
|
||||||
|
return self[key]
|
||||||
|
except KeyError:
|
||||||
|
self[key] = default
|
||||||
|
return default
|
||||||
|
|
||||||
def new(self, values=None):
|
def new(self, values=None):
|
||||||
"""
|
"""
|
||||||
Returns a new context with the same properties, but with only the
|
Returns a new context with the same properties, but with only the
|
||||||
|
|
|
@ -420,6 +420,13 @@ dictionary syntax::
|
||||||
Returns the value for ``key`` if ``key`` is in the context, else returns
|
Returns the value for ``key`` if ``key`` is in the context, else returns
|
||||||
``otherwise``.
|
``otherwise``.
|
||||||
|
|
||||||
|
.. method:: Context.setdefault(key, default=None)
|
||||||
|
|
||||||
|
.. versionadded:: 1.9
|
||||||
|
|
||||||
|
If ``key`` is in the context, returns its value. Otherwise inserts ``key``
|
||||||
|
with a value of ``default`` and returns ``default``.
|
||||||
|
|
||||||
.. method:: Context.pop()
|
.. method:: Context.pop()
|
||||||
.. method:: Context.push()
|
.. method:: Context.push()
|
||||||
.. exception:: ContextPopException
|
.. exception:: ContextPopException
|
||||||
|
|
|
@ -166,6 +166,9 @@ Templates
|
||||||
helper can now store results in a template variable by using the ``as``
|
helper can now store results in a template variable by using the ``as``
|
||||||
argument.
|
argument.
|
||||||
|
|
||||||
|
* Added a :meth:`Context.setdefault() <django.template.Context.setdefault>`
|
||||||
|
method.
|
||||||
|
|
||||||
Requests and Responses
|
Requests and Responses
|
||||||
^^^^^^^^^^^^^^^^^^^^^^
|
^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
|
||||||
|
|
|
@ -30,6 +30,17 @@ class ContextTests(SimpleTestCase):
|
||||||
self.assertEqual(c['a'], 3)
|
self.assertEqual(c['a'], 3)
|
||||||
self.assertEqual(c['a'], 1)
|
self.assertEqual(c['a'], 1)
|
||||||
|
|
||||||
|
def test_setdefault(self):
|
||||||
|
c = Context()
|
||||||
|
|
||||||
|
x = c.setdefault('x', 42)
|
||||||
|
self.assertEqual(x, 42)
|
||||||
|
self.assertEqual(c['x'], 42)
|
||||||
|
|
||||||
|
x = c.setdefault('x', 100)
|
||||||
|
self.assertEqual(x, 42)
|
||||||
|
self.assertEqual(c['x'], 42)
|
||||||
|
|
||||||
def test_resolve_on_context_method(self):
|
def test_resolve_on_context_method(self):
|
||||||
"""
|
"""
|
||||||
#17778 -- Variable shouldn't resolve RequestContext methods
|
#17778 -- Variable shouldn't resolve RequestContext methods
|
||||||
|
|
Loading…
Reference in New Issue