Django

Code

root/django/trunk/tests/modeltests/field_defaults/models.py

Revision 8532, 1.5 kB (checked in by mtredinnick, 4 days ago)

Fixed #7464 -- Fixed the psycopg2 backend to handle SafeString? values as
parameters. Based on a patch from Digitalxero@gmail.com.

  • Property svn:eol-style set to native
Line 
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 """}
Note: See TracBrowser for help on using the browser.