1
# -*- coding: utf-8 -*-
3
>>> from django.forms import *
4
>>> from django.forms.widgets import RadioFieldRenderer
5
>>> from django.core.files.uploadedfile import SimpleUploadedFile
10
... from decimal import Decimal
11
... except ImportError:
12
... from django.utils._decimal import Decimal
19
Each Field class does some sort of validation. Each Field has a clean() method,
20
which either raises django.forms.ValidationError or returns the "clean"
21
data -- usually a Unicode object, but, in some rare cases, a list.
23
Each Field's __init__() takes at least these parameters:
24
required -- Boolean that specifies whether the field is required.
26
widget -- A Widget class, or instance of a Widget class, that should be
27
used for this Field when displaying it. Each Field has a default
28
Widget that it'll use if you don't specify this. In most cases,
29
the default widget is TextInput.
30
label -- A verbose name for this field, for use in displaying this field in
31
a form. By default, Django will use a "pretty" version of the form
32
field name, if the Field is part of a Form.
33
initial -- A value to use in this Field's initial display. This value is
34
*not* used as a fallback if data isn't given.
36
Other than that, the Field subclasses have class-specific options for
37
__init__(). For example, CharField has a max_length option.
39
# CharField ###################################################################
47
Traceback (most recent call last):
49
ValidationError: [u'This field is required.']
51
Traceback (most recent call last):
53
ValidationError: [u'This field is required.']
54
>>> f.clean([1, 2, 3])
57
>>> f = CharField(required=False)
66
>>> f.clean([1, 2, 3])
69
CharField accepts an optional max_length parameter:
70
>>> f = CharField(max_length=10, required=False)
73
>>> f.clean('1234567890')
75
>>> f.clean('1234567890a')
76
Traceback (most recent call last):
78
ValidationError: [u'Ensure this value has at most 10 characters (it has 11).']
80
CharField accepts an optional min_length parameter:
81
>>> f = CharField(min_length=10, required=False)
85
Traceback (most recent call last):
87
ValidationError: [u'Ensure this value has at least 10 characters (it has 5).']
88
>>> f.clean('1234567890')
90
>>> f.clean('1234567890a')
93
>>> f = CharField(min_length=10, required=True)
95
Traceback (most recent call last):
97
ValidationError: [u'This field is required.']
99
Traceback (most recent call last):
101
ValidationError: [u'Ensure this value has at least 10 characters (it has 5).']
102
>>> f.clean('1234567890')
104
>>> f.clean('1234567890a')
107
# IntegerField ################################################################
109
>>> f = IntegerField()
111
Traceback (most recent call last):
113
ValidationError: [u'This field is required.']
115
Traceback (most recent call last):
117
ValidationError: [u'This field is required.']
120
>>> isinstance(f.clean('1'), int)
125
Traceback (most recent call last):
127
ValidationError: [u'Enter a whole number.']
131
Traceback (most recent call last):
133
ValidationError: [u'Enter a whole number.']
141
Traceback (most recent call last):
143
ValidationError: [u'Enter a whole number.']
145
>>> f = IntegerField(required=False)
147
>>> repr(f.clean(''))
150
>>> repr(f.clean(None))
154
>>> isinstance(f.clean('1'), int)
159
Traceback (most recent call last):
161
ValidationError: [u'Enter a whole number.']
169
Traceback (most recent call last):
171
ValidationError: [u'Enter a whole number.']
173
IntegerField accepts an optional max_value parameter:
174
>>> f = IntegerField(max_value=10)
176
Traceback (most recent call last):
178
ValidationError: [u'This field is required.']
184
Traceback (most recent call last):
186
ValidationError: [u'Ensure this value is less than or equal to 10.']
190
Traceback (most recent call last):
192
ValidationError: [u'Ensure this value is less than or equal to 10.']
194
IntegerField accepts an optional min_value parameter:
195
>>> f = IntegerField(min_value=10)
197
Traceback (most recent call last):
199
ValidationError: [u'This field is required.']
201
Traceback (most recent call last):
203
ValidationError: [u'Ensure this value is greater than or equal to 10.']
213
min_value and max_value can be used together:
214
>>> f = IntegerField(min_value=10, max_value=20)
216
Traceback (most recent call last):
218
ValidationError: [u'This field is required.']
220
Traceback (most recent call last):
222
ValidationError: [u'Ensure this value is greater than or equal to 10.']
234
Traceback (most recent call last):
236
ValidationError: [u'Ensure this value is less than or equal to 20.']
238
# FloatField ##################################################################
242
Traceback (most recent call last):
244
ValidationError: [u'This field is required.']
246
Traceback (most recent call last):
248
ValidationError: [u'This field is required.']
251
>>> isinstance(f.clean('1'), float)
262
Traceback (most recent call last):
264
ValidationError: [u'Enter a number.']
272
Traceback (most recent call last):
274
ValidationError: [u'Enter a number.']
276
>>> f = FloatField(required=False)
284
FloatField accepts min_value and max_value just like IntegerField:
285
>>> f = FloatField(max_value=1.5, min_value=0.5)
288
Traceback (most recent call last):
290
ValidationError: [u'Ensure this value is less than or equal to 1.5.']
292
Traceback (most recent call last):
294
ValidationError: [u'Ensure this value is greater than or equal to 0.5.']
300
# DecimalField ################################################################
302
>>> f = DecimalField(max_digits=4, decimal_places=2)
304
Traceback (most recent call last):
306
ValidationError: [u'This field is required.']
308
Traceback (most recent call last):
310
ValidationError: [u'This field is required.']
311
>>> f.clean('1') == Decimal("1")
313
>>> isinstance(f.clean('1'), Decimal)
315
>>> f.clean('23') == Decimal("23")
317
>>> f.clean('3.14') == Decimal("3.14")
319
>>> f.clean(3.14) == Decimal("3.14")
321
>>> f.clean(Decimal('3.14')) == Decimal("3.14")
324
Traceback (most recent call last):
326
ValidationError: [u'Enter a number.']
328
Traceback (most recent call last):
330
ValidationError: [u'Enter a number.']
331
>>> f.clean('1.0 ') == Decimal("1.0")
333
>>> f.clean(' 1.0') == Decimal("1.0")
335
>>> f.clean(' 1.0 ') == Decimal("1.0")
338
Traceback (most recent call last):
340
ValidationError: [u'Enter a number.']
341
>>> f.clean('123.45')
342
Traceback (most recent call last):
344
ValidationError: [u'Ensure that there are no more than 4 digits in total.']
346
Traceback (most recent call last):
348
ValidationError: [u'Ensure that there are no more than 2 decimal places.']
350
Traceback (most recent call last):
352
ValidationError: [u'Ensure that there are no more than 2 digits before the decimal point.']
353
>>> f.clean('-12.34') == Decimal("-12.34")
355
>>> f.clean('-123.45')
356
Traceback (most recent call last):
358
ValidationError: [u'Ensure that there are no more than 4 digits in total.']
359
>>> f.clean('-.12') == Decimal("-0.12")
361
>>> f.clean('-00.12') == Decimal("-0.12")
363
>>> f.clean('-000.12') == Decimal("-0.12")
365
>>> f.clean('-000.123')
366
Traceback (most recent call last):
368
ValidationError: [u'Ensure that there are no more than 2 decimal places.']
369
>>> f.clean('-000.1234')
370
Traceback (most recent call last):
372
ValidationError: [u'Ensure that there are no more than 4 digits in total.']
373
>>> f.clean('--0.12')
374
Traceback (most recent call last):
376
ValidationError: [u'Enter a number.']
378
>>> f = DecimalField(max_digits=4, decimal_places=2, required=False)
383
>>> f.clean('1') == Decimal("1")
386
DecimalField accepts min_value and max_value just like IntegerField:
387
>>> f = DecimalField(max_digits=4, decimal_places=2, max_value=Decimal('1.5'), min_value=Decimal('0.5'))
390
Traceback (most recent call last):
392
ValidationError: [u'Ensure this value is less than or equal to 1.5.']
394
Traceback (most recent call last):
396
ValidationError: [u'Ensure this value is greater than or equal to 0.5.']
397
>>> f.clean('1.5') == Decimal("1.5")
399
>>> f.clean('0.5') == Decimal("0.5")
401
>>> f.clean('.5') == Decimal("0.5")
403
>>> f.clean('00.50') == Decimal("0.50")
407
>>> f = DecimalField(decimal_places=2)
408
>>> f.clean('0.00000001')
409
Traceback (most recent call last):
411
ValidationError: [u'Ensure that there are no more than 2 decimal places.']
414
>>> f = DecimalField(max_digits=3)
416
# Leading whole zeros "collapse" to one digit.
417
>>> f.clean('0000000.10') == Decimal("0.1")
419
>>> f.clean('0000000.100')
420
Traceback (most recent call last):
422
ValidationError: [u'Ensure that there are no more than 3 digits in total.']
424
# Only leading whole zeros "collapse" to one digit.
425
>>> f.clean('000000.02') == Decimal('0.02')
427
>>> f.clean('000000.002')
428
Traceback (most recent call last):
430
ValidationError: [u'Ensure that there are no more than 3 digits in total.']
433
# DateField ###################################################################
437
>>> f.clean(datetime.date(2006, 10, 25))
438
datetime.date(2006, 10, 25)
439
>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30))
440
datetime.date(2006, 10, 25)
441
>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))
442
datetime.date(2006, 10, 25)
443
>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))
444
datetime.date(2006, 10, 25)
445
>>> f.clean('2006-10-25')
446
datetime.date(2006, 10, 25)
447
>>> f.clean('10/25/2006')
448
datetime.date(2006, 10, 25)
449
>>> f.clean('10/25/06')
450
datetime.date(2006, 10, 25)
451
>>> f.clean('Oct 25 2006')
452
datetime.date(2006, 10, 25)
453
>>> f.clean('October 25 2006')
454
datetime.date(2006, 10, 25)
455
>>> f.clean('October 25, 2006')
456
datetime.date(2006, 10, 25)
457
>>> f.clean('25 October 2006')
458
datetime.date(2006, 10, 25)
459
>>> f.clean('25 October, 2006')
460
datetime.date(2006, 10, 25)
461
>>> f.clean('2006-4-31')
462
Traceback (most recent call last):
464
ValidationError: [u'Enter a valid date.']
465
>>> f.clean('200a-10-25')
466
Traceback (most recent call last):
468
ValidationError: [u'Enter a valid date.']
469
>>> f.clean('25/10/06')
470
Traceback (most recent call last):
472
ValidationError: [u'Enter a valid date.']
474
Traceback (most recent call last):
476
ValidationError: [u'This field is required.']
478
>>> f = DateField(required=False)
480
>>> repr(f.clean(None))
483
>>> repr(f.clean(''))
486
DateField accepts an optional input_formats parameter:
487
>>> f = DateField(input_formats=['%Y %m %d'])
488
>>> f.clean(datetime.date(2006, 10, 25))
489
datetime.date(2006, 10, 25)
490
>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30))
491
datetime.date(2006, 10, 25)
492
>>> f.clean('2006 10 25')
493
datetime.date(2006, 10, 25)
495
The input_formats parameter overrides all default input formats,
496
so the default formats won't work unless you specify them:
497
>>> f.clean('2006-10-25')
498
Traceback (most recent call last):
500
ValidationError: [u'Enter a valid date.']
501
>>> f.clean('10/25/2006')
502
Traceback (most recent call last):
504
ValidationError: [u'Enter a valid date.']
505
>>> f.clean('10/25/06')
506
Traceback (most recent call last):
508
ValidationError: [u'Enter a valid date.']
510
# TimeField ###################################################################
514
>>> f.clean(datetime.time(14, 25))
515
datetime.time(14, 25)
516
>>> f.clean(datetime.time(14, 25, 59))
517
datetime.time(14, 25, 59)
519
datetime.time(14, 25)
520
>>> f.clean('14:25:59')
521
datetime.time(14, 25, 59)
523
Traceback (most recent call last):
525
ValidationError: [u'Enter a valid time.']
526
>>> f.clean('1:24 p.m.')
527
Traceback (most recent call last):
529
ValidationError: [u'Enter a valid time.']
531
TimeField accepts an optional input_formats parameter:
532
>>> f = TimeField(input_formats=['%I:%M %p'])
533
>>> f.clean(datetime.time(14, 25))
534
datetime.time(14, 25)
535
>>> f.clean(datetime.time(14, 25, 59))
536
datetime.time(14, 25, 59)
537
>>> f.clean('4:25 AM')
539
>>> f.clean('4:25 PM')
540
datetime.time(16, 25)
542
The input_formats parameter overrides all default input formats,
543
so the default formats won't work unless you specify them:
544
>>> f.clean('14:30:45')
545
Traceback (most recent call last):
547
ValidationError: [u'Enter a valid time.']
549
# DateTimeField ###############################################################
552
>>> f = DateTimeField()
553
>>> f.clean(datetime.date(2006, 10, 25))
554
datetime.datetime(2006, 10, 25, 0, 0)
555
>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30))
556
datetime.datetime(2006, 10, 25, 14, 30)
557
>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))
558
datetime.datetime(2006, 10, 25, 14, 30, 59)
559
>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))
560
datetime.datetime(2006, 10, 25, 14, 30, 59, 200)
561
>>> f.clean('2006-10-25 14:30:45')
562
datetime.datetime(2006, 10, 25, 14, 30, 45)
563
>>> f.clean('2006-10-25 14:30:00')
564
datetime.datetime(2006, 10, 25, 14, 30)
565
>>> f.clean('2006-10-25 14:30')
566
datetime.datetime(2006, 10, 25, 14, 30)
567
>>> f.clean('2006-10-25')
568
datetime.datetime(2006, 10, 25, 0, 0)
569
>>> f.clean('10/25/2006 14:30:45')
570
datetime.datetime(2006, 10, 25, 14, 30, 45)
571
>>> f.clean('10/25/2006 14:30:00')
572
datetime.datetime(2006, 10, 25, 14, 30)
573
>>> f.clean('10/25/2006 14:30')
574
datetime.datetime(2006, 10, 25, 14, 30)
575
>>> f.clean('10/25/2006')
576
datetime.datetime(2006, 10, 25, 0, 0)
577
>>> f.clean('10/25/06 14:30:45')
578
datetime.datetime(2006, 10, 25, 14, 30, 45)
579
>>> f.clean('10/25/06 14:30:00')
580
datetime.datetime(2006, 10, 25, 14, 30)
581
>>> f.clean('10/25/06 14:30')
582
datetime.datetime(2006, 10, 25, 14, 30)
583
>>> f.clean('10/25/06')
584
datetime.datetime(2006, 10, 25, 0, 0)
586
Traceback (most recent call last):
588
ValidationError: [u'Enter a valid date/time.']
589
>>> f.clean('2006-10-25 4:30 p.m.')
590
Traceback (most recent call last):
592
ValidationError: [u'Enter a valid date/time.']
594
DateField accepts an optional input_formats parameter:
595
>>> f = DateTimeField(input_formats=['%Y %m %d %I:%M %p'])
596
>>> f.clean(datetime.date(2006, 10, 25))
597
datetime.datetime(2006, 10, 25, 0, 0)
598
>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30))
599
datetime.datetime(2006, 10, 25, 14, 30)
600
>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59))
601
datetime.datetime(2006, 10, 25, 14, 30, 59)
602
>>> f.clean(datetime.datetime(2006, 10, 25, 14, 30, 59, 200))
603
datetime.datetime(2006, 10, 25, 14, 30, 59, 200)
604
>>> f.clean('2006 10 25 2:30 PM')
605
datetime.datetime(2006, 10, 25, 14, 30)
607
The input_formats parameter overrides all default input formats,
608
so the default formats won't work unless you specify them:
609
>>> f.clean('2006-10-25 14:30:45')
610
Traceback (most recent call last):
612
ValidationError: [u'Enter a valid date/time.']
614
>>> f = DateTimeField(required=False)
616
>>> repr(f.clean(None))
619
>>> repr(f.clean(''))
622
# RegexField ##################################################################
624
>>> f = RegexField('^\d[A-F]\d$')
630
Traceback (most recent call last):
632
ValidationError: [u'Enter a valid value.']
634
Traceback (most recent call last):
636
ValidationError: [u'Enter a valid value.']
638
Traceback (most recent call last):
640
ValidationError: [u'Enter a valid value.']
642
Traceback (most recent call last):
644
ValidationError: [u'This field is required.']
646
>>> f = RegexField('^\d[A-F]\d$', required=False)
652
Traceback (most recent call last):
654
ValidationError: [u'Enter a valid value.']
658
Alternatively, RegexField can take a compiled regular expression:
659
>>> f = RegexField(re.compile('^\d[A-F]\d$'))
665
Traceback (most recent call last):
667
ValidationError: [u'Enter a valid value.']
669
Traceback (most recent call last):
671
ValidationError: [u'Enter a valid value.']
673
Traceback (most recent call last):
675
ValidationError: [u'Enter a valid value.']
677
RegexField takes an optional error_message argument:
678
>>> f = RegexField('^\d\d\d\d$', error_message='Enter a four-digit number.')
682
Traceback (most recent call last):
684
ValidationError: [u'Enter a four-digit number.']
686
Traceback (most recent call last):
688
ValidationError: [u'Enter a four-digit number.']
690
RegexField also access min_length and max_length parameters, for convenience.
691
>>> f = RegexField('^\d+$', min_length=5, max_length=10)
693
Traceback (most recent call last):
695
ValidationError: [u'Ensure this value has at least 5 characters (it has 3).']
697
Traceback (most recent call last):
699
ValidationError: [u'Ensure this value has at least 5 characters (it has 3).']
702
>>> f.clean('1234567890')
704
>>> f.clean('12345678901')
705
Traceback (most recent call last):
707
ValidationError: [u'Ensure this value has at most 10 characters (it has 11).']
708
>>> f.clean('12345a')
709
Traceback (most recent call last):
711
ValidationError: [u'Enter a valid value.']
713
# EmailField ##################################################################
717
Traceback (most recent call last):
719
ValidationError: [u'This field is required.']
721
Traceback (most recent call last):
723
ValidationError: [u'This field is required.']
724
>>> f.clean('person@example.com')
725
u'person@example.com'
727
Traceback (most recent call last):
729
ValidationError: [u'Enter a valid e-mail address.']
731
Traceback (most recent call last):
733
ValidationError: [u'Enter a valid e-mail address.']
734
>>> f.clean('foo@bar')
735
Traceback (most recent call last):
737
ValidationError: [u'Enter a valid e-mail address.']
739
>>> f = EmailField(required=False)
744
>>> f.clean('person@example.com')
745
u'person@example.com'
747
Traceback (most recent call last):
749
ValidationError: [u'Enter a valid e-mail address.']
751
Traceback (most recent call last):
753
ValidationError: [u'Enter a valid e-mail address.']
754
>>> f.clean('foo@bar')
755
Traceback (most recent call last):
757
ValidationError: [u'Enter a valid e-mail address.']
759
EmailField also access min_length and max_length parameters, for convenience.
760
>>> f = EmailField(min_length=10, max_length=15)
761
>>> f.clean('a@foo.com')
762
Traceback (most recent call last):
764
ValidationError: [u'Ensure this value has at least 10 characters (it has 9).']
765
>>> f.clean('alf@foo.com')
767
>>> f.clean('alf123456788@foo.com')
768
Traceback (most recent call last):
770
ValidationError: [u'Ensure this value has at most 15 characters (it has 20).']
772
# FileField ##################################################################
776
Traceback (most recent call last):
778
ValidationError: [u'This field is required.']
781
Traceback (most recent call last):
783
ValidationError: [u'This field is required.']
785
>>> f.clean('', 'files/test1.pdf')
789
Traceback (most recent call last):
791
ValidationError: [u'This field is required.']
793
>>> f.clean(None, '')
794
Traceback (most recent call last):
796
ValidationError: [u'This field is required.']
798
>>> f.clean(None, 'files/test2.pdf')
801
>>> f.clean(SimpleUploadedFile('', ''))
802
Traceback (most recent call last):
804
ValidationError: [u'No file was submitted. Check the encoding type on the form.']
806
>>> f.clean(SimpleUploadedFile('', ''), '')
807
Traceback (most recent call last):
809
ValidationError: [u'No file was submitted. Check the encoding type on the form.']
811
>>> f.clean(None, 'files/test3.pdf')
814
>>> f.clean('some content that is not a file')
815
Traceback (most recent call last):
817
ValidationError: [u'No file was submitted. Check the encoding type on the form.']
819
>>> f.clean(SimpleUploadedFile('name', None))
820
Traceback (most recent call last):
822
ValidationError: [u'The submitted file is empty.']
824
>>> f.clean(SimpleUploadedFile('name', ''))
825
Traceback (most recent call last):
827
ValidationError: [u'The submitted file is empty.']
829
>>> type(f.clean(SimpleUploadedFile('name', 'Some File Content')))
830
<class 'django.core.files.uploadedfile.SimpleUploadedFile'>
832
>>> type(f.clean(SimpleUploadedFile('我隻氣墊船裝滿晒鱔.txt', 'मेरी मँडराने वाली नाव सर्पमीनों से भरी ह')))
833
<class 'django.core.files.uploadedfile.SimpleUploadedFile'>
835
>>> type(f.clean(SimpleUploadedFile('name', 'Some File Content'), 'files/test4.pdf'))
836
<class 'django.core.files.uploadedfile.SimpleUploadedFile'>
838
# URLField ##################################################################
842
Traceback (most recent call last):
844
ValidationError: [u'This field is required.']
846
Traceback (most recent call last):
848
ValidationError: [u'This field is required.']
849
>>> f.clean('http://localhost')
851
>>> f.clean('http://example.com')
852
u'http://example.com/'
853
>>> f.clean('http://www.example.com')
854
u'http://www.example.com/'
855
>>> f.clean('http://www.example.com:8000/test')
856
u'http://www.example.com:8000/test'
857
>>> f.clean('http://200.8.9.10')
858
u'http://200.8.9.10/'
859
>>> f.clean('http://200.8.9.10:8000/test')
860
u'http://200.8.9.10:8000/test'
862
Traceback (most recent call last):
864
ValidationError: [u'Enter a valid URL.']
865
>>> f.clean('http://')
866
Traceback (most recent call last):
868
ValidationError: [u'Enter a valid URL.']
869
>>> f.clean('http://example')
870
Traceback (most recent call last):
872
ValidationError: [u'Enter a valid URL.']
873
>>> f.clean('http://example.')
874
Traceback (most recent call last):
876
ValidationError: [u'Enter a valid URL.']
877
>>> f.clean('http://.com')
878
Traceback (most recent call last):
880
ValidationError: [u'Enter a valid URL.']
882
>>> f = URLField(required=False)
887
>>> f.clean('http://example.com')
888
u'http://example.com/'
889
>>> f.clean('http://www.example.com')
890
u'http://www.example.com/'
892
Traceback (most recent call last):
894
ValidationError: [u'Enter a valid URL.']
895
>>> f.clean('http://')
896
Traceback (most recent call last):
898
ValidationError: [u'Enter a valid URL.']
899
>>> f.clean('http://example')
900
Traceback (most recent call last):
902
ValidationError: [u'Enter a valid URL.']
903
>>> f.clean('http://example.')
904
Traceback (most recent call last):
906
ValidationError: [u'Enter a valid URL.']
907
>>> f.clean('http://.com')
908
Traceback (most recent call last):
910
ValidationError: [u'Enter a valid URL.']
912
URLField takes an optional verify_exists parameter, which is False by default.
913
This verifies that the URL is live on the Internet and doesn't return a 404 or 500:
914
>>> f = URLField(verify_exists=True)
915
>>> f.clean('http://www.google.com') # This will fail if there's no Internet connection
916
u'http://www.google.com/'
917
>>> f.clean('http://example')
918
Traceback (most recent call last):
920
ValidationError: [u'Enter a valid URL.']
921
>>> f.clean('http://www.broken.djangoproject.com') # bad domain
922
Traceback (most recent call last):
924
ValidationError: [u'This URL appears to be a broken link.']
925
>>> f.clean('http://google.com/we-love-microsoft.html') # good domain, bad page
926
Traceback (most recent call last):
928
ValidationError: [u'This URL appears to be a broken link.']
929
>>> f = URLField(verify_exists=True, required=False)
932
>>> f.clean('http://www.google.com') # This will fail if there's no Internet connection
933
u'http://www.google.com/'
935
URLField also access min_length and max_length parameters, for convenience.
936
>>> f = URLField(min_length=15, max_length=20)
937
>>> f.clean('http://f.com')
938
Traceback (most recent call last):
940
ValidationError: [u'Ensure this value has at least 15 characters (it has 13).']
941
>>> f.clean('http://example.com')
942
u'http://example.com/'
943
>>> f.clean('http://abcdefghijklmnopqrstuvwxyz.com')
944
Traceback (most recent call last):
946
ValidationError: [u'Ensure this value has at most 20 characters (it has 38).']
948
URLField should prepend 'http://' if no scheme was given
949
>>> f = URLField(required=False)
950
>>> f.clean('example.com')
951
u'http://example.com/'
954
>>> f.clean('https://example.com')
955
u'https://example.com/'
957
URLField should append '/' if no path was given
959
>>> f.clean('http://example.com')
960
u'http://example.com/'
962
URLField shouldn't change the path if it was given
963
>>> f.clean('http://example.com/test')
964
u'http://example.com/test'
966
# BooleanField ################################################################
968
>>> f = BooleanField()
970
Traceback (most recent call last):
972
ValidationError: [u'This field is required.']
974
Traceback (most recent call last):
976
ValidationError: [u'This field is required.']
980
Traceback (most recent call last):
982
ValidationError: [u'This field is required.']
986
Traceback (most recent call last):
988
ValidationError: [u'This field is required.']
989
>>> f.clean('Django rocks')
995
Traceback (most recent call last):
997
ValidationError: [u'This field is required.']
999
>>> f = BooleanField(required=False)
1012
>>> f.clean('Django rocks')
1015
A form's BooleanField with a hidden widget will output the string 'False', so
1016
that should clean to the boolean value False:
1017
>>> f.clean('False')
1020
# ChoiceField #################################################################
1022
>>> f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')])
1024
Traceback (most recent call last):
1026
ValidationError: [u'This field is required.']
1028
Traceback (most recent call last):
1030
ValidationError: [u'This field is required.']
1036
Traceback (most recent call last):
1038
ValidationError: [u'Select a valid choice. 3 is not one of the available choices.']
1040
>>> f = ChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
1050
Traceback (most recent call last):
1052
ValidationError: [u'Select a valid choice. 3 is not one of the available choices.']
1054
>>> f = ChoiceField(choices=[('J', 'John'), ('P', 'Paul')])
1058
Traceback (most recent call last):
1060
ValidationError: [u'Select a valid choice. John is not one of the available choices.']
1062
>>> f = ChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')])
1076
Traceback (most recent call last):
1078
ValidationError: [u'Select a valid choice. 6 is not one of the available choices.']
1080
# TypedChoiceField ############################################################
1082
# TypedChoiceField is just like ChoiceField, except that coerced types will
1084
>>> f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int)
1088
Traceback (most recent call last):
1090
ValidationError: [u'Select a valid choice. 2 is not one of the available choices.']
1092
# Different coercion, same validation.
1093
>>> f.coerce = float
1098
# This can also cause weirdness: be careful (bool(-1) == True, remember)
1103
# Even more weirdness: if you have a valid choice but your coercion function
1104
# can't coerce, you'll still get a validation error. Don't do this!
1105
>>> f = TypedChoiceField(choices=[('A', 'A'), ('B', 'B')], coerce=int)
1107
Traceback (most recent call last):
1109
ValidationError: [u'Select a valid choice. B is not one of the available choices.']
1111
# Required fields require values
1113
Traceback (most recent call last):
1115
ValidationError: [u'This field is required.']
1117
# Non-required fields aren't required
1118
>>> f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False)
1122
# If you want cleaning an empty value to return a different type, tell the field
1123
>>> f = TypedChoiceField(choices=[(1, "+1"), (-1, "-1")], coerce=int, required=False, empty_value=None)
1124
>>> print f.clean('')
1127
# NullBooleanField ############################################################
1129
>>> f = NullBooleanField()
1139
>>> f.clean('hello')
1141
# Make sure that the internal value is preserved if using HiddenInput (#7753)
1142
>>> class HiddenNullBooleanForm(Form):
1143
... hidden_nullbool1 = NullBooleanField(widget=HiddenInput, initial=True)
1144
... hidden_nullbool2 = NullBooleanField(widget=HiddenInput, initial=False)
1145
>>> f = HiddenNullBooleanForm()
1147
<input type="hidden" name="hidden_nullbool1" value="True" id="id_hidden_nullbool1" /><input type="hidden" name="hidden_nullbool2" value="False" id="id_hidden_nullbool2" />
1148
>>> f = HiddenNullBooleanForm({ 'hidden_nullbool1': 'True', 'hidden_nullbool2': 'False' })
1150
>>> f.cleaned_data['hidden_nullbool1']
1152
>>> f.cleaned_data['hidden_nullbool2']
1155
# MultipleChoiceField #########################################################
1157
>>> f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')])
1159
Traceback (most recent call last):
1161
ValidationError: [u'This field is required.']
1163
Traceback (most recent call last):
1165
ValidationError: [u'This field is required.']
1170
>>> f.clean(['1', '2'])
1172
>>> f.clean([1, '2'])
1174
>>> f.clean((1, '2'))
1176
>>> f.clean('hello')
1177
Traceback (most recent call last):
1179
ValidationError: [u'Enter a list of values.']
1181
Traceback (most recent call last):
1183
ValidationError: [u'This field is required.']
1185
Traceback (most recent call last):
1187
ValidationError: [u'This field is required.']
1189
Traceback (most recent call last):
1191
ValidationError: [u'Select a valid choice. 3 is not one of the available choices.']
1193
>>> f = MultipleChoiceField(choices=[('1', 'One'), ('2', 'Two')], required=False)
1202
>>> f.clean(['1', '2'])
1204
>>> f.clean([1, '2'])
1206
>>> f.clean((1, '2'))
1208
>>> f.clean('hello')
1209
Traceback (most recent call last):
1211
ValidationError: [u'Enter a list of values.']
1217
Traceback (most recent call last):
1219
ValidationError: [u'Select a valid choice. 3 is not one of the available choices.']
1221
>>> f = MultipleChoiceField(choices=[('Numbers', (('1', 'One'), ('2', 'Two'))), ('Letters', (('3','A'),('4','B'))), ('5','Other')])
1228
>>> f.clean([1, '5'])
1230
>>> f.clean(['1', 5])
1232
>>> f.clean(['1', '5'])
1235
Traceback (most recent call last):
1237
ValidationError: [u'Select a valid choice. 6 is not one of the available choices.']
1238
>>> f.clean(['1','6'])
1239
Traceback (most recent call last):
1241
ValidationError: [u'Select a valid choice. 6 is not one of the available choices.']
1244
# ComboField ##################################################################
1246
ComboField takes a list of fields that should be used to validate a value,
1248
>>> f = ComboField(fields=[CharField(max_length=20), EmailField()])
1249
>>> f.clean('test@example.com')
1251
>>> f.clean('longemailaddress@example.com')
1252
Traceback (most recent call last):
1254
ValidationError: [u'Ensure this value has at most 20 characters (it has 28).']
1255
>>> f.clean('not an e-mail')
1256
Traceback (most recent call last):
1258
ValidationError: [u'Enter a valid e-mail address.']
1260
Traceback (most recent call last):
1262
ValidationError: [u'This field is required.']
1264
Traceback (most recent call last):
1266
ValidationError: [u'This field is required.']
1268
>>> f = ComboField(fields=[CharField(max_length=20), EmailField()], required=False)
1269
>>> f.clean('test@example.com')
1271
>>> f.clean('longemailaddress@example.com')
1272
Traceback (most recent call last):
1274
ValidationError: [u'Ensure this value has at most 20 characters (it has 28).']
1275
>>> f.clean('not an e-mail')
1276
Traceback (most recent call last):
1278
ValidationError: [u'Enter a valid e-mail address.']
1284
# FilePathField ###############################################################
1286
>>> def fix_os_paths(x):
1287
... if isinstance(x, basestring):
1288
... return x.replace('\\', '/')
1289
... elif isinstance(x, tuple):
1290
... return tuple(fix_os_paths(list(x)))
1291
... elif isinstance(x, list):
1292
... return [fix_os_paths(y) for y in x]
1297
>>> from django import forms
1298
>>> path = forms.__file__
1299
>>> path = os.path.dirname(path) + '/'
1300
>>> fix_os_paths(path)
1302
>>> f = forms.FilePathField(path=path)
1303
>>> f.choices.sort()
1304
>>> fix_os_paths(f.choices)
1305
[('.../django/forms/__init__.py', '__init__.py'), ('.../django/forms/__init__.pyc', '__init__.pyc'), ('.../django/forms/fields.py', 'fields.py'), ('.../django/forms/fields.pyc', 'fields.pyc'), ('.../django/forms/forms.py', 'forms.py'), ('.../django/forms/forms.pyc', 'forms.pyc'), ('.../django/forms/models.py', 'models.py'), ('.../django/forms/models.pyc', 'models.pyc'), ('.../django/forms/util.py', 'util.py'), ('.../django/forms/util.pyc', 'util.pyc'), ('.../django/forms/widgets.py', 'widgets.py'), ('.../django/forms/widgets.pyc', 'widgets.pyc')]
1306
>>> f.clean('fields.py')
1307
Traceback (most recent call last):
1309
ValidationError: [u'Select a valid choice. fields.py is not one of the available choices.']
1310
>>> fix_os_paths(f.clean(path + 'fields.py'))
1311
u'.../django/forms/fields.py'
1312
>>> f = forms.FilePathField(path=path, match='^.*?\.py$')
1313
>>> f.choices.sort()
1314
>>> fix_os_paths(f.choices)
1315
[('.../django/forms/__init__.py', '__init__.py'), ('.../django/forms/fields.py', 'fields.py'), ('.../django/forms/forms.py', 'forms.py'), ('.../django/forms/models.py', 'models.py'), ('.../django/forms/util.py', 'util.py'), ('.../django/forms/widgets.py', 'widgets.py')]
1316
>>> f = forms.FilePathField(path=path, recursive=True, match='^.*?\.py$')
1317
>>> f.choices.sort()
1318
>>> fix_os_paths(f.choices)
1319
[('.../django/forms/__init__.py', '__init__.py'), ('.../django/forms/extras/__init__.py', 'extras/__init__.py'), ('.../django/forms/extras/widgets.py', 'extras/widgets.py'), ('.../django/forms/fields.py', 'fields.py'), ('.../django/forms/forms.py', 'forms.py'), ('.../django/forms/models.py', 'models.py'), ('.../django/forms/util.py', 'util.py'), ('.../django/forms/widgets.py', 'widgets.py')]
1321
# SplitDateTimeField ##########################################################
1323
>>> f = SplitDateTimeField()
1324
>>> f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)])
1325
datetime.datetime(2006, 1, 10, 7, 30)
1327
Traceback (most recent call last):
1329
ValidationError: [u'This field is required.']
1331
Traceback (most recent call last):
1333
ValidationError: [u'This field is required.']
1334
>>> f.clean('hello')
1335
Traceback (most recent call last):
1337
ValidationError: [u'Enter a list of values.']
1338
>>> f.clean(['hello', 'there'])
1339
Traceback (most recent call last):
1341
ValidationError: [u'Enter a valid date.', u'Enter a valid time.']
1342
>>> f.clean(['2006-01-10', 'there'])
1343
Traceback (most recent call last):
1345
ValidationError: [u'Enter a valid time.']
1346
>>> f.clean(['hello', '07:30'])
1347
Traceback (most recent call last):
1349
ValidationError: [u'Enter a valid date.']
1351
>>> f = SplitDateTimeField(required=False)
1352
>>> f.clean([datetime.date(2006, 1, 10), datetime.time(7, 30)])
1353
datetime.datetime(2006, 1, 10, 7, 30)
1354
>>> f.clean(['2006-01-10', '07:30'])
1355
datetime.datetime(2006, 1, 10, 7, 30)
1359
>>> f.clean(['', ''])
1360
>>> f.clean('hello')
1361
Traceback (most recent call last):
1363
ValidationError: [u'Enter a list of values.']
1364
>>> f.clean(['hello', 'there'])
1365
Traceback (most recent call last):
1367
ValidationError: [u'Enter a valid date.', u'Enter a valid time.']
1368
>>> f.clean(['2006-01-10', 'there'])
1369
Traceback (most recent call last):
1371
ValidationError: [u'Enter a valid time.']
1372
>>> f.clean(['hello', '07:30'])
1373
Traceback (most recent call last):
1375
ValidationError: [u'Enter a valid date.']
1376
>>> f.clean(['2006-01-10', ''])
1377
Traceback (most recent call last):
1379
ValidationError: [u'Enter a valid time.']
1380
>>> f.clean(['2006-01-10'])
1381
Traceback (most recent call last):
1383
ValidationError: [u'Enter a valid time.']
1384
>>> f.clean(['', '07:30'])
1385
Traceback (most recent call last):
1387
ValidationError: [u'Enter a valid date.']