~ubuntu-branches/ubuntu/quantal/python-django/quantal

« back to all changes in this revision

Viewing changes to tests/modeltests/field_defaults/models.py

  • Committer: Bazaar Package Importer
  • Author(s): Scott James Remnant
  • Date: 2008-11-15 19:15:33 UTC
  • mfrom: (1.1.6 upstream)
  • Revision ID: james.westby@ubuntu.com-20081115191533-xbt1ut2xf4fvwtvc
Tags: 1.0.1-0ubuntu1
* New upstream release:
  - Bug fixes.

* The tests/ sub-directory appaers to have been dropped upstream, so pull
  our patch to workaround the tests and modify the rules.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
"""
2
 
32. Callable defaults
3
 
 
4
 
You can pass callable objects as the ``default`` parameter to a field. When
5
 
the object is created without an explicit value passed in, Django will call
6
 
the method to determine the default value.
7
 
 
8
 
This example uses ``datetime.datetime.now`` as the default for the ``pub_date``
9
 
field.
10
 
"""
11
 
 
12
 
from django.db import models
13
 
from datetime import datetime
14
 
 
15
 
class Article(models.Model):
16
 
    headline = models.CharField(max_length=100, default='Default headline')
17
 
    pub_date = models.DateTimeField(default=datetime.now)
18
 
 
19
 
    def __unicode__(self):
20
 
        return self.headline
21
 
 
22
 
__test__ = {'API_TESTS':"""
23
 
>>> from datetime import datetime
24
 
 
25
 
# No articles are in the system yet.
26
 
>>> Article.objects.all()
27
 
[]
28
 
 
29
 
# Create an Article.
30
 
>>> a = Article(id=None)
31
 
 
32
 
# Grab the current datetime it should be very close to the default that just
33
 
# got saved as a.pub_date
34
 
>>> now = datetime.now()
35
 
 
36
 
# Save it into the database. You have to call save() explicitly.
37
 
>>> a.save()
38
 
 
39
 
# Now it has an ID. Note it's a long integer, as designated by the trailing "L".
40
 
>>> a.id
41
 
1L
42
 
 
43
 
# Access database columns via Python attributes.
44
 
>>> a.headline
45
 
u'Default headline'
46
 
 
47
 
# make sure the two dates are sufficiently close
48
 
>>> d = now - a.pub_date
49
 
>>> d.seconds < 5
50
 
True
51
 
 
52
 
# make sure that SafeString/SafeUnicode fields work
53
 
>>> from django.utils.safestring import SafeUnicode, SafeString
54
 
>>> a.headline = SafeUnicode(u'SafeUnicode Headline')
55
 
>>> a.save()
56
 
>>> a.headline = SafeString(u'SafeString Headline')
57
 
>>> a.save()
58
 
"""}