Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Beginnings of test conversion.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@15653 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit 380906b94659930be656e929ff417bd474f6e81a 1 parent 312d2f3
Alex Gaynor authored February 26, 2011
1,359  tests/modeltests/model_forms/models.py
@@ -240,1361 +240,4 @@ class FlexibleDatePost(models.Model):
240 240
     title = models.CharField(max_length=50, unique_for_date='posted', blank=True)
241 241
     slug = models.CharField(max_length=50, unique_for_year='posted', blank=True)
242 242
     subtitle = models.CharField(max_length=50, unique_for_month='posted', blank=True)
243  
-    posted = models.DateField(blank=True, null=True)
244  
-
245  
-__test__ = {'API_TESTS': """
246  
->>> from django import forms
247  
->>> from django.forms.models import ModelForm, model_to_dict
248  
->>> from django.core.files.uploadedfile import SimpleUploadedFile
249  
-
250  
-The bare bones, absolutely nothing custom, basic case.
251  
-
252  
->>> class CategoryForm(ModelForm):
253  
-...     class Meta:
254  
-...         model = Category
255  
->>> CategoryForm.base_fields.keys()
256  
-['name', 'slug', 'url']
257  
-
258  
-
259  
-Extra fields.
260  
-
261  
->>> class CategoryForm(ModelForm):
262  
-...     some_extra_field = forms.BooleanField()
263  
-...
264  
-...     class Meta:
265  
-...         model = Category
266  
-
267  
->>> CategoryForm.base_fields.keys()
268  
-['name', 'slug', 'url', 'some_extra_field']
269  
-
270  
-Extra field that has a name collision with a related object accessor.
271  
-
272  
->>> class WriterForm(ModelForm):
273  
-...     book = forms.CharField(required=False)
274  
-...
275  
-...     class Meta:
276  
-...         model = Writer
277  
-
278  
->>> wf = WriterForm({'name': 'Richard Lockridge'})
279  
->>> wf.is_valid()
280  
-True
281  
-
282  
-Replacing a field.
283  
-
284  
->>> class CategoryForm(ModelForm):
285  
-...     url = forms.BooleanField()
286  
-...
287  
-...     class Meta:
288  
-...         model = Category
289  
-
290  
->>> CategoryForm.base_fields['url'].__class__
291  
-<class 'django.forms.fields.BooleanField'>
292  
-
293  
-
294  
-Using 'fields'.
295  
-
296  
->>> class CategoryForm(ModelForm):
297  
-...
298  
-...     class Meta:
299  
-...         model = Category
300  
-...         fields = ['url']
301  
-
302  
->>> CategoryForm.base_fields.keys()
303  
-['url']
304  
-
305  
-
306  
-Using 'exclude'
307  
-
308  
->>> class CategoryForm(ModelForm):
309  
-...
310  
-...     class Meta:
311  
-...         model = Category
312  
-...         exclude = ['url']
313  
-
314  
->>> CategoryForm.base_fields.keys()
315  
-['name', 'slug']
316  
-
317  
-
318  
-Using 'fields' *and* 'exclude'. Not sure why you'd want to do this, but uh,
319  
-"be liberal in what you accept" and all.
320  
-
321  
->>> class CategoryForm(ModelForm):
322  
-...
323  
-...     class Meta:
324  
-...         model = Category
325  
-...         fields = ['name', 'url']
326  
-...         exclude = ['url']
327  
-
328  
->>> CategoryForm.base_fields.keys()
329  
-['name']
330  
-
331  
-Using 'widgets'
332  
-
333  
->>> class CategoryForm(ModelForm):
334  
-...
335  
-...     class Meta:
336  
-...         model = Category
337  
-...         fields = ['name', 'url', 'slug']
338  
-...         widgets = {
339  
-...             'name': forms.Textarea,
340  
-...             'url': forms.TextInput(attrs={'class': 'url'})
341  
-...         }
342  
-
343  
->>> str(CategoryForm()['name'])
344  
-'<textarea id="id_name" rows="10" cols="40" name="name"></textarea>'
345  
-
346  
->>> str(CategoryForm()['url'])
347  
-'<input id="id_url" type="text" class="url" name="url" maxlength="40" />'
348  
-
349  
->>> str(CategoryForm()['slug'])
350  
-'<input id="id_slug" type="text" name="slug" maxlength="20" />'
351  
-
352  
-Don't allow more than one 'model' definition in the inheritance hierarchy.
353  
-Technically, it would generate a valid form, but the fact that the resulting
354  
-save method won't deal with multiple objects is likely to trip up people not
355  
-familiar with the mechanics.
356  
-
357  
->>> class CategoryForm(ModelForm):
358  
-...     class Meta:
359  
-...         model = Category
360  
-
361  
->>> class OddForm(CategoryForm):
362  
-...     class Meta:
363  
-...         model = Article
364  
-
365  
-OddForm is now an Article-related thing, because BadForm.Meta overrides
366  
-CategoryForm.Meta.
367  
->>> OddForm.base_fields.keys()
368  
-['headline', 'slug', 'pub_date', 'writer', 'article', 'status', 'categories']
369  
-
370  
->>> class ArticleForm(ModelForm):
371  
-...     class Meta:
372  
-...         model = Article
373  
-
374  
-First class with a Meta class wins.
375  
-
376  
->>> class BadForm(ArticleForm, CategoryForm):
377  
-...     pass
378  
->>> OddForm.base_fields.keys()
379  
-['headline', 'slug', 'pub_date', 'writer', 'article', 'status', 'categories']
380  
-
381  
-Subclassing without specifying a Meta on the class will use the parent's Meta
382  
-(or the first parent in the MRO if there are multiple parent classes).
383  
-
384  
->>> class CategoryForm(ModelForm):
385  
-...     class Meta:
386  
-...         model = Category
387  
->>> class SubCategoryForm(CategoryForm):
388  
-...     pass
389  
->>> SubCategoryForm.base_fields.keys()
390  
-['name', 'slug', 'url']
391  
-
392  
-We can also subclass the Meta inner class to change the fields list.
393  
-
394  
->>> class CategoryForm(ModelForm):
395  
-...     checkbox = forms.BooleanField()
396  
-...
397  
-...     class Meta:
398  
-...         model = Category
399  
->>> class SubCategoryForm(CategoryForm):
400  
-...     class Meta(CategoryForm.Meta):
401  
-...         exclude = ['url']
402  
-
403  
->>> print SubCategoryForm()
404  
-<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr>
405  
-<tr><th><label for="id_slug">Slug:</label></th><td><input id="id_slug" type="text" name="slug" maxlength="20" /></td></tr>
406  
-<tr><th><label for="id_checkbox">Checkbox:</label></th><td><input type="checkbox" name="checkbox" id="id_checkbox" /></td></tr>
407  
-
408  
-# test using fields to provide ordering to the fields
409  
->>> class CategoryForm(ModelForm):
410  
-...     class Meta:
411  
-...         model = Category
412  
-...         fields = ['url', 'name']
413  
-
414  
->>> CategoryForm.base_fields.keys()
415  
-['url', 'name']
416  
-
417  
-
418  
->>> print CategoryForm()
419  
-<tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr>
420  
-<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr>
421  
-
422  
->>> class CategoryForm(ModelForm):
423  
-...     class Meta:
424  
-...         model = Category
425  
-...         fields = ['slug', 'url', 'name']
426  
-...         exclude = ['url']
427  
-
428  
->>> CategoryForm.base_fields.keys()
429  
-['slug', 'name']
430  
-
431  
-# Old form_for_x tests #######################################################
432  
-
433  
->>> from django.forms import ModelForm, CharField
434  
->>> import datetime
435  
-
436  
->>> Category.objects.all()
437  
-[]
438  
-
439  
->>> class CategoryForm(ModelForm):
440  
-...     class Meta:
441  
-...         model = Category
442  
->>> f = CategoryForm()
443  
->>> print f
444  
-<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr>
445  
-<tr><th><label for="id_slug">Slug:</label></th><td><input id="id_slug" type="text" name="slug" maxlength="20" /></td></tr>
446  
-<tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr>
447  
->>> print f.as_ul()
448  
-<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="20" /></li>
449  
-<li><label for="id_slug">Slug:</label> <input id="id_slug" type="text" name="slug" maxlength="20" /></li>
450  
-<li><label for="id_url">The URL:</label> <input id="id_url" type="text" name="url" maxlength="40" /></li>
451  
->>> print f['name']
452  
-<input id="id_name" type="text" name="name" maxlength="20" />
453  
-
454  
->>> f = CategoryForm(auto_id=False)
455  
->>> print f.as_ul()
456  
-<li>Name: <input type="text" name="name" maxlength="20" /></li>
457  
-<li>Slug: <input type="text" name="slug" maxlength="20" /></li>
458  
-<li>The URL: <input type="text" name="url" maxlength="40" /></li>
459  
-
460  
->>> f = CategoryForm({'name': 'Entertainment', 'slug': 'entertainment', 'url': 'entertainment'})
461  
->>> f.is_valid()
462  
-True
463  
->>> f.cleaned_data['url']
464  
-u'entertainment'
465  
->>> f.cleaned_data['name']
466  
-u'Entertainment'
467  
->>> f.cleaned_data['slug']
468  
-u'entertainment'
469  
->>> obj = f.save()
470  
->>> obj
471  
-<Category: Entertainment>
472  
->>> Category.objects.all()
473  
-[<Category: Entertainment>]
474  
-
475  
->>> f = CategoryForm({'name': "It's a test", 'slug': 'its-test', 'url': 'test'})
476  
->>> f.is_valid()
477  
-True
478  
->>> f.cleaned_data['url']
479  
-u'test'
480  
->>> f.cleaned_data['name']
481  
-u"It's a test"
482  
->>> f.cleaned_data['slug']
483  
-u'its-test'
484  
->>> obj = f.save()
485  
->>> obj
486  
-<Category: It's a test>
487  
->>> Category.objects.order_by('name')
488  
-[<Category: Entertainment>, <Category: It's a test>]
489  
-
490  
-If you call save() with commit=False, then it will return an object that
491  
-hasn't yet been saved to the database. In this case, it's up to you to call
492  
-save() on the resulting model instance.
493  
->>> f = CategoryForm({'name': 'Third test', 'slug': 'third-test', 'url': 'third'})
494  
->>> f.is_valid()
495  
-True
496  
->>> f.cleaned_data['url']
497  
-u'third'
498  
->>> f.cleaned_data['name']
499  
-u'Third test'
500  
->>> f.cleaned_data['slug']
501  
-u'third-test'
502  
->>> obj = f.save(commit=False)
503  
->>> obj
504  
-<Category: Third test>
505  
->>> Category.objects.order_by('name')
506  
-[<Category: Entertainment>, <Category: It's a test>]
507  
->>> obj.save()
508  
->>> Category.objects.order_by('name')
509  
-[<Category: Entertainment>, <Category: It's a test>, <Category: Third test>]
510  
-
511  
-If you call save() with invalid data, you'll get a ValueError.
512  
->>> f = CategoryForm({'name': '', 'slug': 'not a slug!', 'url': 'foo'})
513  
->>> f.errors['name']
514  
-[u'This field is required.']
515  
->>> f.errors['slug']
516  
-[u"Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."]
517  
->>> f.cleaned_data
518  
-Traceback (most recent call last):
519  
-...
520  
-AttributeError: 'CategoryForm' object has no attribute 'cleaned_data'
521  
->>> f.save()
522  
-Traceback (most recent call last):
523  
-...
524  
-ValueError: The Category could not be created because the data didn't validate.
525  
->>> f = CategoryForm({'name': '', 'slug': '', 'url': 'foo'})
526  
->>> f.save()
527  
-Traceback (most recent call last):
528  
-...
529  
-ValueError: The Category could not be created because the data didn't validate.
530  
-
531  
-Create a couple of Writers.
532  
->>> w_royko = Writer(name='Mike Royko')
533  
->>> w_royko.save()
534  
->>> w_woodward = Writer(name='Bob Woodward')
535  
->>> w_woodward.save()
536  
-
537  
-ManyToManyFields are represented by a MultipleChoiceField, ForeignKeys and any
538  
-fields with the 'choices' attribute are represented by a ChoiceField.
539  
->>> class ArticleForm(ModelForm):
540  
-...     class Meta:
541  
-...         model = Article
542  
->>> f = ArticleForm(auto_id=False)
543  
->>> print f
544  
-<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" /></td></tr>
545  
-<tr><th>Slug:</th><td><input type="text" name="slug" maxlength="50" /></td></tr>
546  
-<tr><th>Pub date:</th><td><input type="text" name="pub_date" /></td></tr>
547  
-<tr><th>Writer:</th><td><select name="writer">
548  
-<option value="" selected="selected">---------</option>
549  
-<option value="...">Mike Royko</option>
550  
-<option value="...">Bob Woodward</option>
551  
-</select></td></tr>
552  
-<tr><th>Article:</th><td><textarea rows="10" cols="40" name="article"></textarea></td></tr>
553  
-<tr><th>Status:</th><td><select name="status">
554  
-<option value="" selected="selected">---------</option>
555  
-<option value="1">Draft</option>
556  
-<option value="2">Pending</option>
557  
-<option value="3">Live</option>
558  
-</select></td></tr>
559  
-<tr><th>Categories:</th><td><select multiple="multiple" name="categories">
560  
-<option value="1">Entertainment</option>
561  
-<option value="2">It&#39;s a test</option>
562  
-<option value="3">Third test</option>
563  
-</select><br /><span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></td></tr>
564  
-
565  
-You can restrict a form to a subset of the complete list of fields
566  
-by providing a 'fields' argument. If you try to save a
567  
-model created with such a form, you need to ensure that the fields
568  
-that are _not_ on the form have default values, or are allowed to have
569  
-a value of None. If a field isn't specified on a form, the object created
570  
-from the form can't provide a value for that field!
571  
->>> class PartialArticleForm(ModelForm):
572  
-...     class Meta:
573  
-...         model = Article
574  
-...         fields = ('headline','pub_date')
575  
->>> f = PartialArticleForm(auto_id=False)
576  
->>> print f
577  
-<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" /></td></tr>
578  
-<tr><th>Pub date:</th><td><input type="text" name="pub_date" /></td></tr>
579  
-
580  
-When the ModelForm is passed an instance, that instance's current values are
581  
-inserted as 'initial' data in each Field.
582  
->>> w = Writer.objects.get(name='Mike Royko')
583  
->>> class RoykoForm(ModelForm):
584  
-...     class Meta:
585  
-...         model = Writer
586  
->>> f = RoykoForm(auto_id=False, instance=w)
587  
->>> print f
588  
-<tr><th>Name:</th><td><input type="text" name="name" value="Mike Royko" maxlength="50" /><br /><span class="helptext">Use both first and last names.</span></td></tr>
589  
-
590  
->>> art = Article(headline='Test article', slug='test-article', pub_date=datetime.date(1988, 1, 4), writer=w, article='Hello.')
591  
->>> art.save()
592  
->>> art.id
593  
-1
594  
->>> class TestArticleForm(ModelForm):
595  
-...     class Meta:
596  
-...         model = Article
597  
->>> f = TestArticleForm(auto_id=False, instance=art)
598  
->>> print f.as_ul()
599  
-<li>Headline: <input type="text" name="headline" value="Test article" maxlength="50" /></li>
600  
-<li>Slug: <input type="text" name="slug" value="test-article" maxlength="50" /></li>
601  
-<li>Pub date: <input type="text" name="pub_date" value="1988-01-04" /></li>
602  
-<li>Writer: <select name="writer">
603  
-<option value="">---------</option>
604  
-<option value="..." selected="selected">Mike Royko</option>
605  
-<option value="...">Bob Woodward</option>
606  
-</select></li>
607  
-<li>Article: <textarea rows="10" cols="40" name="article">Hello.</textarea></li>
608  
-<li>Status: <select name="status">
609  
-<option value="" selected="selected">---------</option>
610  
-<option value="1">Draft</option>
611  
-<option value="2">Pending</option>
612  
-<option value="3">Live</option>
613  
-</select></li>
614  
-<li>Categories: <select multiple="multiple" name="categories">
615  
-<option value="1">Entertainment</option>
616  
-<option value="2">It&#39;s a test</option>
617  
-<option value="3">Third test</option>
618  
-</select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>
619  
->>> f = TestArticleForm({'headline': u'Test headline', 'slug': 'test-headline', 'pub_date': u'1984-02-06', 'writer': unicode(w_royko.pk), 'article': 'Hello.'}, instance=art)
620  
->>> f.errors
621  
-{}
622  
->>> f.is_valid()
623  
-True
624  
->>> test_art = f.save()
625  
->>> test_art.id
626  
-1
627  
->>> test_art = Article.objects.get(id=1)
628  
->>> test_art.headline
629  
-u'Test headline'
630  
-
631  
-You can create a form over a subset of the available fields
632  
-by specifying a 'fields' argument to form_for_instance.
633  
->>> class PartialArticleForm(ModelForm):
634  
-...     class Meta:
635  
-...         model = Article
636  
-...         fields=('headline', 'slug', 'pub_date')
637  
->>> f = PartialArticleForm({'headline': u'New headline', 'slug': 'new-headline', 'pub_date': u'1988-01-04'}, auto_id=False, instance=art)
638  
->>> print f.as_ul()
639  
-<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" /></li>
640  
-<li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" /></li>
641  
-<li>Pub date: <input type="text" name="pub_date" value="1988-01-04" /></li>
642  
->>> f.is_valid()
643  
-True
644  
->>> new_art = f.save()
645  
->>> new_art.id
646  
-1
647  
->>> new_art = Article.objects.get(id=1)
648  
->>> new_art.headline
649  
-u'New headline'
650  
-
651  
-Add some categories and test the many-to-many form output.
652  
->>> new_art.categories.all()
653  
-[]
654  
->>> new_art.categories.add(Category.objects.get(name='Entertainment'))
655  
->>> new_art.categories.all()
656  
-[<Category: Entertainment>]
657  
->>> class TestArticleForm(ModelForm):
658  
-...     class Meta:
659  
-...         model = Article
660  
->>> f = TestArticleForm(auto_id=False, instance=new_art)
661  
->>> print f.as_ul()
662  
-<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" /></li>
663  
-<li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" /></li>
664  
-<li>Pub date: <input type="text" name="pub_date" value="1988-01-04" /></li>
665  
-<li>Writer: <select name="writer">
666  
-<option value="">---------</option>
667  
-<option value="..." selected="selected">Mike Royko</option>
668  
-<option value="...">Bob Woodward</option>
669  
-</select></li>
670  
-<li>Article: <textarea rows="10" cols="40" name="article">Hello.</textarea></li>
671  
-<li>Status: <select name="status">
672  
-<option value="" selected="selected">---------</option>
673  
-<option value="1">Draft</option>
674  
-<option value="2">Pending</option>
675  
-<option value="3">Live</option>
676  
-</select></li>
677  
-<li>Categories: <select multiple="multiple" name="categories">
678  
-<option value="1" selected="selected">Entertainment</option>
679  
-<option value="2">It&#39;s a test</option>
680  
-<option value="3">Third test</option>
681  
-</select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>
682  
-
683  
-Initial values can be provided for model forms
684  
->>> f = TestArticleForm(auto_id=False, initial={'headline': 'Your headline here', 'categories': ['1','2']})
685  
->>> print f.as_ul()
686  
-<li>Headline: <input type="text" name="headline" value="Your headline here" maxlength="50" /></li>
687  
-<li>Slug: <input type="text" name="slug" maxlength="50" /></li>
688  
-<li>Pub date: <input type="text" name="pub_date" /></li>
689  
-<li>Writer: <select name="writer">
690  
-<option value="" selected="selected">---------</option>
691  
-<option value="...">Mike Royko</option>
692  
-<option value="...">Bob Woodward</option>
693  
-</select></li>
694  
-<li>Article: <textarea rows="10" cols="40" name="article"></textarea></li>
695  
-<li>Status: <select name="status">
696  
-<option value="" selected="selected">---------</option>
697  
-<option value="1">Draft</option>
698  
-<option value="2">Pending</option>
699  
-<option value="3">Live</option>
700  
-</select></li>
701  
-<li>Categories: <select multiple="multiple" name="categories">
702  
-<option value="1" selected="selected">Entertainment</option>
703  
-<option value="2" selected="selected">It&#39;s a test</option>
704  
-<option value="3">Third test</option>
705  
-</select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>
706  
-
707  
->>> f = TestArticleForm({'headline': u'New headline', 'slug': u'new-headline', 'pub_date': u'1988-01-04',
708  
-...     'writer': unicode(w_royko.pk), 'article': u'Hello.', 'categories': [u'1', u'2']}, instance=new_art)
709  
->>> new_art = f.save()
710  
->>> new_art.id
711  
-1
712  
->>> new_art = Article.objects.get(id=1)
713  
->>> new_art.categories.order_by('name')
714  
-[<Category: Entertainment>, <Category: It's a test>]
715  
-
716  
-Now, submit form data with no categories. This deletes the existing categories.
717  
->>> f = TestArticleForm({'headline': u'New headline', 'slug': u'new-headline', 'pub_date': u'1988-01-04',
718  
-...     'writer': unicode(w_royko.pk), 'article': u'Hello.'}, instance=new_art)
719  
->>> new_art = f.save()
720  
->>> new_art.id
721  
-1
722  
->>> new_art = Article.objects.get(id=1)
723  
->>> new_art.categories.all()
724  
-[]
725  
-
726  
-Create a new article, with categories, via the form.
727  
->>> class ArticleForm(ModelForm):
728  
-...     class Meta:
729  
-...         model = Article
730  
->>> f = ArticleForm({'headline': u'The walrus was Paul', 'slug': u'walrus-was-paul', 'pub_date': u'1967-11-01',
731  
-...     'writer': unicode(w_royko.pk), 'article': u'Test.', 'categories': [u'1', u'2']})
732  
->>> new_art = f.save()
733  
->>> new_art.id
734  
-2
735  
->>> new_art = Article.objects.get(id=2)
736  
->>> new_art.categories.order_by('name')
737  
-[<Category: Entertainment>, <Category: It's a test>]
738  
-
739  
-Create a new article, with no categories, via the form.
740  
->>> class ArticleForm(ModelForm):
741  
-...     class Meta:
742  
-...         model = Article
743  
->>> f = ArticleForm({'headline': u'The walrus was Paul', 'slug': u'walrus-was-paul', 'pub_date': u'1967-11-01',
744  
-...     'writer': unicode(w_royko.pk), 'article': u'Test.'})
745  
->>> new_art = f.save()
746  
->>> new_art.id
747  
-3
748  
->>> new_art = Article.objects.get(id=3)
749  
->>> new_art.categories.all()
750  
-[]
751  
-
752  
-Create a new article, with categories, via the form, but use commit=False.
753  
-The m2m data won't be saved until save_m2m() is invoked on the form.
754  
->>> class ArticleForm(ModelForm):
755  
-...     class Meta:
756  
-...         model = Article
757  
->>> f = ArticleForm({'headline': u'The walrus was Paul', 'slug': 'walrus-was-paul', 'pub_date': u'1967-11-01',
758  
-...     'writer': unicode(w_royko.pk), 'article': u'Test.', 'categories': [u'1', u'2']})
759  
->>> new_art = f.save(commit=False)
760  
-
761  
-# Manually save the instance
762  
->>> new_art.save()
763  
->>> new_art.id
764  
-4
765  
-
766  
-# The instance doesn't have m2m data yet
767  
->>> new_art = Article.objects.get(id=4)
768  
->>> new_art.categories.all()
769  
-[]
770  
-
771  
-# Save the m2m data on the form
772  
->>> f.save_m2m()
773  
->>> new_art.categories.order_by('name')
774  
-[<Category: Entertainment>, <Category: It's a test>]
775  
-
776  
-Here, we define a custom ModelForm. Because it happens to have the same fields as
777  
-the Category model, we can just call the form's save() to apply its changes to an
778  
-existing Category instance.
779  
->>> class ShortCategory(ModelForm):
780  
-...     name = CharField(max_length=5)
781  
-...     slug = CharField(max_length=5)
782  
-...     url = CharField(max_length=3)
783  
->>> cat = Category.objects.get(name='Third test')
784  
->>> cat
785  
-<Category: Third test>
786  
->>> cat.id
787  
-3
788  
->>> form = ShortCategory({'name': 'Third', 'slug': 'third', 'url': '3rd'}, instance=cat)
789  
->>> form.save()
790  
-<Category: Third>
791  
->>> Category.objects.get(id=3)
792  
-<Category: Third>
793  
-
794  
-Here, we demonstrate that choices for a ForeignKey ChoiceField are determined
795  
-at runtime, based on the data in the database when the form is displayed, not
796  
-the data in the database when the form is instantiated.
797  
->>> class ArticleForm(ModelForm):
798  
-...     class Meta:
799  
-...         model = Article
800  
->>> f = ArticleForm(auto_id=False)
801  
->>> print f.as_ul()
802  
-<li>Headline: <input type="text" name="headline" maxlength="50" /></li>
803  
-<li>Slug: <input type="text" name="slug" maxlength="50" /></li>
804  
-<li>Pub date: <input type="text" name="pub_date" /></li>
805  
-<li>Writer: <select name="writer">
806  
-<option value="" selected="selected">---------</option>
807  
-<option value="...">Mike Royko</option>
808  
-<option value="...">Bob Woodward</option>
809  
-</select></li>
810  
-<li>Article: <textarea rows="10" cols="40" name="article"></textarea></li>
811  
-<li>Status: <select name="status">
812  
-<option value="" selected="selected">---------</option>
813  
-<option value="1">Draft</option>
814  
-<option value="2">Pending</option>
815  
-<option value="3">Live</option>
816  
-</select></li>
817  
-<li>Categories: <select multiple="multiple" name="categories">
818  
-<option value="1">Entertainment</option>
819  
-<option value="2">It&#39;s a test</option>
820  
-<option value="3">Third</option>
821  
-</select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>
822  
->>> Category.objects.create(name='Fourth', url='4th')
823  
-<Category: Fourth>
824  
->>> Writer.objects.create(name='Carl Bernstein')
825  
-<Writer: Carl Bernstein>
826  
->>> print f.as_ul()
827  
-<li>Headline: <input type="text" name="headline" maxlength="50" /></li>
828  
-<li>Slug: <input type="text" name="slug" maxlength="50" /></li>
829  
-<li>Pub date: <input type="text" name="pub_date" /></li>
830  
-<li>Writer: <select name="writer">
831  
-<option value="" selected="selected">---------</option>
832  
-<option value="...">Mike Royko</option>
833  
-<option value="...">Bob Woodward</option>
834  
-<option value="...">Carl Bernstein</option>
835  
-</select></li>
836  
-<li>Article: <textarea rows="10" cols="40" name="article"></textarea></li>
837  
-<li>Status: <select name="status">
838  
-<option value="" selected="selected">---------</option>
839  
-<option value="1">Draft</option>
840  
-<option value="2">Pending</option>
841  
-<option value="3">Live</option>
842  
-</select></li>
843  
-<li>Categories: <select multiple="multiple" name="categories">
844  
-<option value="1">Entertainment</option>
845  
-<option value="2">It&#39;s a test</option>
846  
-<option value="3">Third</option>
847  
-<option value="4">Fourth</option>
848  
-</select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>
849  
-
850  
-# ModelChoiceField ############################################################
851  
-
852  
->>> from django.forms import ModelChoiceField, ModelMultipleChoiceField
853  
-
854  
->>> f = ModelChoiceField(Category.objects.all())
855  
->>> list(f.choices)
856  
-[(u'', u'---------'), (1, u'Entertainment'), (2, u"It's a test"), (3, u'Third'), (4, u'Fourth')]
857  
->>> f.clean('')
858  
-Traceback (most recent call last):
859  
-...
860  
-ValidationError: [u'This field is required.']
861  
->>> f.clean(None)
862  
-Traceback (most recent call last):
863  
-...
864  
-ValidationError: [u'This field is required.']
865  
->>> f.clean(0)
866  
-Traceback (most recent call last):
867  
-...
868  
-ValidationError: [u'Select a valid choice. That choice is not one of the available choices.']
869  
->>> f.clean(3)
870  
-<Category: Third>
871  
->>> f.clean(2)
872  
-<Category: It's a test>
873  
-
874  
-# Add a Category object *after* the ModelChoiceField has already been
875  
-# instantiated. This proves clean() checks the database during clean() rather
876  
-# than caching it at time of instantiation.
877  
->>> Category.objects.create(name='Fifth', url='5th')
878  
-<Category: Fifth>
879  
->>> f.clean(5)
880  
-<Category: Fifth>
881  
-
882  
-# Delete a Category object *after* the ModelChoiceField has already been
883  
-# instantiated. This proves clean() checks the database during clean() rather
884  
-# than caching it at time of instantiation.
885  
->>> Category.objects.get(url='5th').delete()
886  
->>> f.clean(5)
887  
-Traceback (most recent call last):
888  
-...
889  
-ValidationError: [u'Select a valid choice. That choice is not one of the available choices.']
890  
-
891  
->>> f = ModelChoiceField(Category.objects.filter(pk=1), required=False)
892  
->>> print f.clean('')
893  
-None
894  
->>> f.clean('')
895  
->>> f.clean('1')
896  
-<Category: Entertainment>
897  
->>> f.clean('100')
898  
-Traceback (most recent call last):
899  
-...
900  
-ValidationError: [u'Select a valid choice. That choice is not one of the available choices.']
901  
-
902  
-# queryset can be changed after the field is created.
903  
->>> f.queryset = Category.objects.exclude(name='Fourth')
904  
->>> list(f.choices)
905  
-[(u'', u'---------'), (1, u'Entertainment'), (2, u"It's a test"), (3, u'Third')]
906  
->>> f.clean(3)
907  
-<Category: Third>
908  
->>> f.clean(4)
909  
-Traceback (most recent call last):
910  
-...
911  
-ValidationError: [u'Select a valid choice. That choice is not one of the available choices.']
912  
-
913  
-# check that we can safely iterate choices repeatedly
914  
->>> gen_one = list(f.choices)
915  
->>> gen_two = f.choices
916  
->>> gen_one[2]
917  
-(2L, u"It's a test")
918  
->>> list(gen_two)
919  
-[(u'', u'---------'), (1L, u'Entertainment'), (2L, u"It's a test"), (3L, u'Third')]
920  
-
921  
-# check that we can override the label_from_instance method to print custom labels (#4620)
922  
->>> f.queryset = Category.objects.all()
923  
->>> f.label_from_instance = lambda obj: "category " + str(obj)
924  
->>> list(f.choices)
925  
-[(u'', u'---------'), (1L, 'category Entertainment'), (2L, "category It's a test"), (3L, 'category Third'), (4L, 'category Fourth')]
926  
-
927  
-# ModelMultipleChoiceField ####################################################
928  
-
929  
->>> f = ModelMultipleChoiceField(Category.objects.all())
930  
->>> list(f.choices)
931  
-[(1, u'Entertainment'), (2, u"It's a test"), (3, u'Third'), (4, u'Fourth')]
932  
->>> f.clean(None)
933  
-Traceback (most recent call last):
934  
-...
935  
-ValidationError: [u'This field is required.']
936  
->>> f.clean([])
937  
-Traceback (most recent call last):
938  
-...
939  
-ValidationError: [u'This field is required.']
940  
->>> f.clean([1])
941  
-[<Category: Entertainment>]
942  
->>> f.clean([2])
943  
-[<Category: It's a test>]
944  
->>> f.clean(['1'])
945  
-[<Category: Entertainment>]
946  
->>> f.clean(['1', '2'])
947  
-[<Category: Entertainment>, <Category: It's a test>]
948  
->>> f.clean([1, '2'])
949  
-[<Category: Entertainment>, <Category: It's a test>]
950  
->>> f.clean((1, '2'))
951  
-[<Category: Entertainment>, <Category: It's a test>]
952  
->>> f.clean(['100'])
953  
-Traceback (most recent call last):
954  
-...
955  
-ValidationError: [u'Select a valid choice. 100 is not one of the available choices.']
956  
->>> f.clean('hello')
957  
-Traceback (most recent call last):
958  
-...
959  
-ValidationError: [u'Enter a list of values.']
960  
->>> f.clean(['fail'])
961  
-Traceback (most recent call last):
962  
-...
963  
-ValidationError: [u'"fail" is not a valid value for a primary key.']
964  
-
965  
-# Add a Category object *after* the ModelMultipleChoiceField has already been
966  
-# instantiated. This proves clean() checks the database during clean() rather
967  
-# than caching it at time of instantiation.
968  
->>> Category.objects.create(id=6, name='Sixth', url='6th')
969  
-<Category: Sixth>
970  
->>> f.clean([6])
971  
-[<Category: Sixth>]
972  
-
973  
-# Delete a Category object *after* the ModelMultipleChoiceField has already been
974  
-# instantiated. This proves clean() checks the database during clean() rather
975  
-# than caching it at time of instantiation.
976  
->>> Category.objects.get(url='6th').delete()
977  
->>> f.clean([6])
978  
-Traceback (most recent call last):
979  
-...
980  
-ValidationError: [u'Select a valid choice. 6 is not one of the available choices.']
981  
-
982  
->>> f = ModelMultipleChoiceField(Category.objects.all(), required=False)
983  
->>> f.clean([])
984  
-[]
985  
->>> f.clean(())
986  
-[]
987  
->>> f.clean(['10'])
988  
-Traceback (most recent call last):
989  
-...
990  
-ValidationError: [u'Select a valid choice. 10 is not one of the available choices.']
991  
->>> f.clean(['3', '10'])
992  
-Traceback (most recent call last):
993  
-...
994  
-ValidationError: [u'Select a valid choice. 10 is not one of the available choices.']
995  
->>> f.clean(['1', '10'])
996  
-Traceback (most recent call last):
997  
-...
998  
-ValidationError: [u'Select a valid choice. 10 is not one of the available choices.']
999  
-
1000  
-# queryset can be changed after the field is created.
1001  
->>> f.queryset = Category.objects.exclude(name='Fourth')
1002  
->>> list(f.choices)
1003  
-[(1, u'Entertainment'), (2, u"It's a test"), (3, u'Third')]
1004  
->>> f.clean([3])
1005  
-[<Category: Third>]
1006  
->>> f.clean([4])
1007  
-Traceback (most recent call last):
1008  
-...
1009  
-ValidationError: [u'Select a valid choice. 4 is not one of the available choices.']
1010  
->>> f.clean(['3', '4'])
1011  
-Traceback (most recent call last):
1012  
-...
1013  
-ValidationError: [u'Select a valid choice. 4 is not one of the available choices.']
1014  
-
1015  
->>> f.queryset = Category.objects.all()
1016  
->>> f.label_from_instance = lambda obj: "multicategory " + str(obj)
1017  
->>> list(f.choices)
1018  
-[(1L, 'multicategory Entertainment'), (2L, "multicategory It's a test"), (3L, 'multicategory Third'), (4L, 'multicategory Fourth')]
1019  
-
1020  
-# OneToOneField ###############################################################
1021  
-
1022  
->>> class ImprovedArticleForm(ModelForm):
1023  
-...     class Meta:
1024  
-...         model = ImprovedArticle
1025  
->>> ImprovedArticleForm.base_fields.keys()
1026  
-['article']
1027  
-
1028  
->>> class ImprovedArticleWithParentLinkForm(ModelForm):
1029  
-...     class Meta:
1030  
-...         model = ImprovedArticleWithParentLink
1031  
->>> ImprovedArticleWithParentLinkForm.base_fields.keys()
1032  
-[]
1033  
-
1034  
->>> bw = BetterWriter(name=u'Joe Better', score=10)
1035  
->>> bw.save()
1036  
->>> sorted(model_to_dict(bw).keys())
1037  
-['id', 'name', 'score', 'writer_ptr']
1038  
-
1039  
->>> class BetterWriterForm(ModelForm):
1040  
-...     class Meta:
1041  
-...         model = BetterWriter
1042  
->>> form = BetterWriterForm({'name': 'Some Name', 'score': 12})
1043  
->>> form.is_valid()
1044  
-True
1045  
->>> bw2 = form.save()
1046  
->>> bw2.delete()
1047  
-
1048  
-
1049  
->>> class WriterProfileForm(ModelForm):
1050  
-...     class Meta:
1051  
-...         model = WriterProfile
1052  
->>> form = WriterProfileForm()
1053  
->>> print form.as_p()
1054  
-<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer">
1055  
-<option value="" selected="selected">---------</option>
1056  
-<option value="...">Mike Royko</option>
1057  
-<option value="...">Bob Woodward</option>
1058  
-<option value="...">Carl Bernstein</option>
1059  
-<option value="...">Joe Better</option>
1060  
-</select></p>
1061  
-<p><label for="id_age">Age:</label> <input type="text" name="age" id="id_age" /></p>
1062  
-
1063  
->>> data = {
1064  
-...     'writer': unicode(w_woodward.pk),
1065  
-...     'age': u'65',
1066  
-... }
1067  
->>> form = WriterProfileForm(data)
1068  
->>> instance = form.save()
1069  
->>> instance
1070  
-<WriterProfile: Bob Woodward is 65>
1071  
-
1072  
->>> form = WriterProfileForm(instance=instance)
1073  
->>> print form.as_p()
1074  
-<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer">
1075  
-<option value="">---------</option>
1076  
-<option value="...">Mike Royko</option>
1077  
-<option value="..." selected="selected">Bob Woodward</option>
1078  
-<option value="...">Carl Bernstein</option>
1079  
-<option value="...">Joe Better</option>
1080  
-</select></p>
1081  
-<p><label for="id_age">Age:</label> <input type="text" name="age" value="65" id="id_age" /></p>
1082  
-
1083  
-# PhoneNumberField ############################################################
1084  
-
1085  
->>> class PhoneNumberForm(ModelForm):
1086  
-...     class Meta:
1087  
-...         model = PhoneNumber
1088  
->>> f = PhoneNumberForm({'phone': '(312) 555-1212', 'description': 'Assistance'})
1089  
->>> f.is_valid()
1090  
-True
1091  
->>> f.cleaned_data['phone']
1092  
-u'312-555-1212'
1093  
->>> f.cleaned_data['description']
1094  
-u'Assistance'
1095  
-
1096  
-# FileField ###################################################################
1097  
-
1098  
-# File forms.
1099  
-
1100  
->>> class TextFileForm(ModelForm):
1101  
-...     class Meta:
1102  
-...         model = TextFile
1103  
-
1104  
-# Test conditions when files is either not given or empty.
1105  
-
1106  
->>> f = TextFileForm(data={'description': u'Assistance'})
1107  
->>> f.is_valid()
1108  
-False
1109  
->>> f = TextFileForm(data={'description': u'Assistance'}, files={})
1110  
->>> f.is_valid()
1111  
-False
1112  
-
1113  
-# Upload a file and ensure it all works as expected.
1114  
-
1115  
->>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': SimpleUploadedFile('test1.txt', 'hello world')})
1116  
->>> f.is_valid()
1117  
-True
1118  
->>> type(f.cleaned_data['file'])
1119  
-<class 'django.core.files.uploadedfile.SimpleUploadedFile'>
1120  
->>> instance = f.save()
1121  
->>> instance.file
1122  
-<FieldFile: tests/test1.txt>
1123  
-
1124  
->>> instance.file.delete()
1125  
-
1126  
->>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': SimpleUploadedFile('test1.txt', 'hello world')})
1127  
->>> f.is_valid()
1128  
-True
1129  
->>> type(f.cleaned_data['file'])
1130  
-<class 'django.core.files.uploadedfile.SimpleUploadedFile'>
1131  
->>> instance = f.save()
1132  
->>> instance.file
1133  
-<FieldFile: tests/test1.txt>
1134  
-
1135  
-# Check if the max_length attribute has been inherited from the model.
1136  
->>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': SimpleUploadedFile('test-maxlength.txt', 'hello world')})
1137  
->>> f.is_valid()
1138  
-False
1139  
-
1140  
-# Edit an instance that already has the file defined in the model. This will not
1141  
-# save the file again, but leave it exactly as it is.
1142  
-
1143  
->>> f = TextFileForm(data={'description': u'Assistance'}, instance=instance)
1144  
->>> f.is_valid()
1145  
-True
1146  
->>> f.cleaned_data['file']
1147  
-<FieldFile: tests/test1.txt>
1148  
->>> instance = f.save()
1149  
->>> instance.file
1150  
-<FieldFile: tests/test1.txt>
1151  
-
1152  
-# Delete the current file since this is not done by Django.
1153  
->>> instance.file.delete()
1154  
-
1155  
-# Override the file by uploading a new one.
1156  
-
1157  
->>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': SimpleUploadedFile('test2.txt', 'hello world')}, instance=instance)
1158  
->>> f.is_valid()
1159  
-True
1160  
->>> instance = f.save()
1161  
->>> instance.file
1162  
-<FieldFile: tests/test2.txt>
1163  
-
1164  
-# Delete the current file since this is not done by Django.
1165  
->>> instance.file.delete()
1166  
-
1167  
->>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': SimpleUploadedFile('test2.txt', 'hello world')})
1168  
->>> f.is_valid()
1169  
-True
1170  
->>> instance = f.save()
1171  
->>> instance.file
1172  
-<FieldFile: tests/test2.txt>
1173  
-
1174  
-# Delete the current file since this is not done by Django.
1175  
->>> instance.file.delete()
1176  
-
1177  
->>> instance.delete()
1178  
-
1179  
-# Test the non-required FileField
1180  
->>> f = TextFileForm(data={'description': u'Assistance'})
1181  
->>> f.fields['file'].required = False
1182  
->>> f.is_valid()
1183  
-True
1184  
->>> instance = f.save()
1185  
->>> instance.file
1186  
-<FieldFile: None>
1187  
-
1188  
->>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': SimpleUploadedFile('test3.txt', 'hello world')}, instance=instance)
1189  
->>> f.is_valid()
1190  
-True
1191  
->>> instance = f.save()
1192  
->>> instance.file
1193  
-<FieldFile: tests/test3.txt>
1194  
-
1195  
-# Instance can be edited w/out re-uploading the file and existing file should be preserved.
1196  
-
1197  
->>> f = TextFileForm(data={'description': u'New Description'}, instance=instance)
1198  
->>> f.fields['file'].required = False
1199  
->>> f.is_valid()
1200  
-True
1201  
->>> instance = f.save()
1202  
->>> instance.description
1203  
-u'New Description'
1204  
->>> instance.file
1205  
-<FieldFile: tests/test3.txt>
1206  
-
1207  
-# Delete the current file since this is not done by Django.
1208  
->>> instance.file.delete()
1209  
->>> instance.delete()
1210  
-
1211  
->>> f = TextFileForm(data={'description': u'Assistance'}, files={'file': SimpleUploadedFile('test3.txt', 'hello world')})
1212  
->>> f.is_valid()
1213  
-True
1214  
->>> instance = f.save()
1215  
->>> instance.file
1216  
-<FieldFile: tests/test3.txt>
1217  
-
1218  
-# Delete the current file since this is not done by Django.
1219  
->>> instance.file.delete()
1220  
->>> instance.delete()
1221  
-
1222  
-# BigIntegerField ################################################################
1223  
->>> class BigIntForm(forms.ModelForm):
1224  
-...     class Meta:
1225  
-...         model = BigInt
1226  
-...
1227  
->>> bif = BigIntForm({'biggie': '-9223372036854775808'})
1228  
->>> bif.is_valid()
1229  
-True
1230  
->>> bif = BigIntForm({'biggie': '-9223372036854775809'})
1231  
->>> bif.is_valid()
1232  
-False
1233  
->>> bif.errors
1234  
-{'biggie': [u'Ensure this value is greater than or equal to -9223372036854775808.']}
1235  
->>> bif = BigIntForm({'biggie': '9223372036854775807'})
1236  
->>> bif.is_valid()
1237  
-True
1238  
->>> bif = BigIntForm({'biggie': '9223372036854775808'})
1239  
->>> bif.is_valid()
1240  
-False
1241  
->>> bif.errors
1242  
-{'biggie': [u'Ensure this value is less than or equal to 9223372036854775807.']}
1243  
-"""}
1244  
-
1245  
-if test_images:
1246  
-    __test__['API_TESTS'] += """
1247  
-# ImageField ###################################################################
1248  
-
1249  
-# ImageField and FileField are nearly identical, but they differ slighty when
1250  
-# it comes to validation. This specifically tests that #6302 is fixed for
1251  
-# both file fields and image fields.
1252  
-
1253  
->>> class ImageFileForm(ModelForm):
1254  
-...     class Meta:
1255  
-...         model = ImageFile
1256  
-
1257  
->>> image_data = open(os.path.join(os.path.dirname(__file__), "test.png"), 'rb').read()
1258  
->>> image_data2 = open(os.path.join(os.path.dirname(__file__), "test2.png"), 'rb').read()
1259  
-
1260  
->>> f = ImageFileForm(data={'description': u'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)})
1261  
->>> f.is_valid()
1262  
-True
1263  
->>> type(f.cleaned_data['image'])
1264  
-<class 'django.core.files.uploadedfile.SimpleUploadedFile'>
1265  
->>> instance = f.save()
1266  
->>> instance.image
1267  
-<...FieldFile: tests/test.png>
1268  
->>> instance.width
1269  
-16
1270  
->>> instance.height
1271  
-16
1272  
-
1273  
-# Delete the current file since this is not done by Django, but don't save
1274  
-# because the dimension fields are not null=True.
1275  
->>> instance.image.delete(save=False)
1276  
-
1277  
->>> f = ImageFileForm(data={'description': u'An image'}, files={'image': SimpleUploadedFile('test.png', image_data)})
1278  
->>> f.is_valid()
1279  
-True
1280  
->>> type(f.cleaned_data['image'])
1281  
-<class 'django.core.files.uploadedfile.SimpleUploadedFile'>
1282  
->>> instance = f.save()
1283  
->>> instance.image
1284  
-<...FieldFile: tests/test.png>
1285  
->>> instance.width
1286  
-16
1287  
->>> instance.height
1288  
-16
1289  
-
1290  
-# Edit an instance that already has the (required) image defined in the model. This will not
1291  
-# save the image again, but leave it exactly as it is.
1292  
-
1293  
->>> f = ImageFileForm(data={'description': u'Look, it changed'}, instance=instance)
1294  
->>> f.is_valid()
1295  
-True
1296  
->>> f.cleaned_data['image']
1297  
-<...FieldFile: tests/test.png>
1298  
->>> instance = f.save()
1299  
->>> instance.image