tests.py 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485
  1. from __future__ import absolute_import
  2. import datetime
  3. import os
  4. from decimal import Decimal
  5. from django import forms
  6. from django.core.files.uploadedfile import SimpleUploadedFile
  7. from django.core.validators import ValidationError
  8. from django.db import connection
  9. from django.forms.models import model_to_dict
  10. from django.utils.unittest import skipUnless
  11. from django.test import TestCase
  12. from .models import (Article, ArticleStatus, BetterWriter, BigInt, Book,
  13. Category, CommaSeparatedInteger, CustomFieldForExclusionModel, DerivedBook,
  14. DerivedPost, ExplicitPK, FlexibleDatePost, ImprovedArticle,
  15. ImprovedArticleWithParentLink, Inventory, PhoneNumber, Post, Price,
  16. Product, TextFile, Writer, WriterProfile, test_images)
  17. if test_images:
  18. from .models import ImageFile, OptionalImageFile
  19. class ImageFileForm(forms.ModelForm):
  20. class Meta:
  21. model = ImageFile
  22. class OptionalImageFileForm(forms.ModelForm):
  23. class Meta:
  24. model = OptionalImageFile
  25. class ProductForm(forms.ModelForm):
  26. class Meta:
  27. model = Product
  28. class PriceForm(forms.ModelForm):
  29. class Meta:
  30. model = Price
  31. class BookForm(forms.ModelForm):
  32. class Meta:
  33. model = Book
  34. class DerivedBookForm(forms.ModelForm):
  35. class Meta:
  36. model = DerivedBook
  37. class ExplicitPKForm(forms.ModelForm):
  38. class Meta:
  39. model = ExplicitPK
  40. fields = ('key', 'desc',)
  41. class PostForm(forms.ModelForm):
  42. class Meta:
  43. model = Post
  44. class DerivedPostForm(forms.ModelForm):
  45. class Meta:
  46. model = DerivedPost
  47. class CustomWriterForm(forms.ModelForm):
  48. name = forms.CharField(required=False)
  49. class Meta:
  50. model = Writer
  51. class FlexDatePostForm(forms.ModelForm):
  52. class Meta:
  53. model = FlexibleDatePost
  54. class BaseCategoryForm(forms.ModelForm):
  55. class Meta:
  56. model = Category
  57. class ArticleForm(forms.ModelForm):
  58. class Meta:
  59. model = Article
  60. class ArticleForm(forms.ModelForm):
  61. class Meta:
  62. model = Article
  63. class PartialArticleForm(forms.ModelForm):
  64. class Meta:
  65. model = Article
  66. fields = ('headline','pub_date')
  67. class RoykoForm(forms.ModelForm):
  68. class Meta:
  69. model = Writer
  70. class TestArticleForm(forms.ModelForm):
  71. class Meta:
  72. model = Article
  73. class PartialArticleFormWithSlug(forms.ModelForm):
  74. class Meta:
  75. model = Article
  76. fields=('headline', 'slug', 'pub_date')
  77. class ArticleStatusForm(forms.ModelForm):
  78. class Meta:
  79. model = ArticleStatus
  80. class InventoryForm(forms.ModelForm):
  81. class Meta:
  82. model = Inventory
  83. class SelectInventoryForm(forms.Form):
  84. items = forms.ModelMultipleChoiceField(Inventory.objects.all(), to_field_name='barcode')
  85. class CustomFieldForExclusionForm(forms.ModelForm):
  86. class Meta:
  87. model = CustomFieldForExclusionModel
  88. fields = ['name', 'markup']
  89. class ShortCategory(forms.ModelForm):
  90. name = forms.CharField(max_length=5)
  91. slug = forms.CharField(max_length=5)
  92. url = forms.CharField(max_length=3)
  93. class ImprovedArticleForm(forms.ModelForm):
  94. class Meta:
  95. model = ImprovedArticle
  96. class ImprovedArticleWithParentLinkForm(forms.ModelForm):
  97. class Meta:
  98. model = ImprovedArticleWithParentLink
  99. class BetterWriterForm(forms.ModelForm):
  100. class Meta:
  101. model = BetterWriter
  102. class WriterProfileForm(forms.ModelForm):
  103. class Meta:
  104. model = WriterProfile
  105. class PhoneNumberForm(forms.ModelForm):
  106. class Meta:
  107. model = PhoneNumber
  108. class TextFileForm(forms.ModelForm):
  109. class Meta:
  110. model = TextFile
  111. class BigIntForm(forms.ModelForm):
  112. class Meta:
  113. model = BigInt
  114. class ModelFormWithMedia(forms.ModelForm):
  115. class Media:
  116. js = ('/some/form/javascript',)
  117. css = {
  118. 'all': ('/some/form/css',)
  119. }
  120. class Meta:
  121. model = PhoneNumber
  122. class CommaSeparatedIntegerForm(forms.ModelForm):
  123. class Meta:
  124. model = CommaSeparatedInteger
  125. class PriceFormWithoutQuantity(forms.ModelForm):
  126. class Meta:
  127. model = Price
  128. exclude = ('quantity',)
  129. class ModelFormBaseTest(TestCase):
  130. def test_base_form(self):
  131. self.assertEqual(BaseCategoryForm.base_fields.keys(),
  132. ['name', 'slug', 'url'])
  133. def test_extra_fields(self):
  134. class ExtraFields(BaseCategoryForm):
  135. some_extra_field = forms.BooleanField()
  136. self.assertEqual(ExtraFields.base_fields.keys(),
  137. ['name', 'slug', 'url', 'some_extra_field'])
  138. def test_replace_field(self):
  139. class ReplaceField(forms.ModelForm):
  140. url = forms.BooleanField()
  141. class Meta:
  142. model = Category
  143. self.assertTrue(isinstance(ReplaceField.base_fields['url'],
  144. forms.fields.BooleanField))
  145. def test_override_field(self):
  146. class WriterForm(forms.ModelForm):
  147. book = forms.CharField(required=False)
  148. class Meta:
  149. model = Writer
  150. wf = WriterForm({'name': 'Richard Lockridge'})
  151. self.assertTrue(wf.is_valid())
  152. def test_limit_fields(self):
  153. class LimitFields(forms.ModelForm):
  154. class Meta:
  155. model = Category
  156. fields = ['url']
  157. self.assertEqual(LimitFields.base_fields.keys(),
  158. ['url'])
  159. def test_exclude_fields(self):
  160. class ExcludeFields(forms.ModelForm):
  161. class Meta:
  162. model = Category
  163. exclude = ['url']
  164. self.assertEqual(ExcludeFields.base_fields.keys(),
  165. ['name', 'slug'])
  166. def test_confused_form(self):
  167. class ConfusedForm(forms.ModelForm):
  168. """ Using 'fields' *and* 'exclude'. Not sure why you'd want to do
  169. this, but uh, "be liberal in what you accept" and all.
  170. """
  171. class Meta:
  172. model = Category
  173. fields = ['name', 'url']
  174. exclude = ['url']
  175. self.assertEqual(ConfusedForm.base_fields.keys(),
  176. ['name'])
  177. def test_mixmodel_form(self):
  178. class MixModelForm(BaseCategoryForm):
  179. """ Don't allow more than one 'model' definition in the
  180. inheritance hierarchy. Technically, it would generate a valid
  181. form, but the fact that the resulting save method won't deal with
  182. multiple objects is likely to trip up people not familiar with the
  183. mechanics.
  184. """
  185. class Meta:
  186. model = Article
  187. # MixModelForm is now an Article-related thing, because MixModelForm.Meta
  188. # overrides BaseCategoryForm.Meta.
  189. self.assertEqual(
  190. MixModelForm.base_fields.keys(),
  191. ['headline', 'slug', 'pub_date', 'writer', 'article', 'categories', 'status']
  192. )
  193. def test_article_form(self):
  194. self.assertEqual(
  195. ArticleForm.base_fields.keys(),
  196. ['headline', 'slug', 'pub_date', 'writer', 'article', 'categories', 'status']
  197. )
  198. def test_bad_form(self):
  199. #First class with a Meta class wins...
  200. class BadForm(ArticleForm, BaseCategoryForm):
  201. pass
  202. self.assertEqual(
  203. BadForm.base_fields.keys(),
  204. ['headline', 'slug', 'pub_date', 'writer', 'article', 'categories', 'status']
  205. )
  206. def test_subcategory_form(self):
  207. class SubCategoryForm(BaseCategoryForm):
  208. """ Subclassing without specifying a Meta on the class will use
  209. the parent's Meta (or the first parent in the MRO if there are
  210. multiple parent classes).
  211. """
  212. pass
  213. self.assertEqual(SubCategoryForm.base_fields.keys(),
  214. ['name', 'slug', 'url'])
  215. def test_subclassmeta_form(self):
  216. class SomeCategoryForm(forms.ModelForm):
  217. checkbox = forms.BooleanField()
  218. class Meta:
  219. model = Category
  220. class SubclassMeta(SomeCategoryForm):
  221. """ We can also subclass the Meta inner class to change the fields
  222. list.
  223. """
  224. class Meta(SomeCategoryForm.Meta):
  225. exclude = ['url']
  226. self.assertHTMLEqual(
  227. str(SubclassMeta()),
  228. """<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr>
  229. <tr><th><label for="id_slug">Slug:</label></th><td><input id="id_slug" type="text" name="slug" maxlength="20" /></td></tr>
  230. <tr><th><label for="id_checkbox">Checkbox:</label></th><td><input type="checkbox" name="checkbox" id="id_checkbox" /></td></tr>"""
  231. )
  232. def test_orderfields_form(self):
  233. class OrderFields(forms.ModelForm):
  234. class Meta:
  235. model = Category
  236. fields = ['url', 'name']
  237. self.assertEqual(OrderFields.base_fields.keys(),
  238. ['url', 'name'])
  239. self.assertHTMLEqual(
  240. str(OrderFields()),
  241. """<tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr>
  242. <tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr>"""
  243. )
  244. def test_orderfields2_form(self):
  245. class OrderFields2(forms.ModelForm):
  246. class Meta:
  247. model = Category
  248. fields = ['slug', 'url', 'name']
  249. exclude = ['url']
  250. self.assertEqual(OrderFields2.base_fields.keys(),
  251. ['slug', 'name'])
  252. class TestWidgetForm(forms.ModelForm):
  253. class Meta:
  254. model = Category
  255. fields = ['name', 'url', 'slug']
  256. widgets = {
  257. 'name': forms.Textarea,
  258. 'url': forms.TextInput(attrs={'class': 'url'})
  259. }
  260. class TestWidgets(TestCase):
  261. def test_base_widgets(self):
  262. frm = TestWidgetForm()
  263. self.assertHTMLEqual(
  264. str(frm['name']),
  265. '<textarea id="id_name" rows="10" cols="40" name="name"></textarea>'
  266. )
  267. self.assertHTMLEqual(
  268. str(frm['url']),
  269. '<input id="id_url" type="text" class="url" name="url" maxlength="40" />'
  270. )
  271. self.assertHTMLEqual(
  272. str(frm['slug']),
  273. '<input id="id_slug" type="text" name="slug" maxlength="20" />'
  274. )
  275. class IncompleteCategoryFormWithFields(forms.ModelForm):
  276. """
  277. A form that replaces the model's url field with a custom one. This should
  278. prevent the model field's validation from being called.
  279. """
  280. url = forms.CharField(required=False)
  281. class Meta:
  282. fields = ('name', 'slug')
  283. model = Category
  284. class IncompleteCategoryFormWithExclude(forms.ModelForm):
  285. """
  286. A form that replaces the model's url field with a custom one. This should
  287. prevent the model field's validation from being called.
  288. """
  289. url = forms.CharField(required=False)
  290. class Meta:
  291. exclude = ['url']
  292. model = Category
  293. class ValidationTest(TestCase):
  294. def test_validates_with_replaced_field_not_specified(self):
  295. form = IncompleteCategoryFormWithFields(data={'name': 'some name', 'slug': 'some-slug'})
  296. assert form.is_valid()
  297. def test_validates_with_replaced_field_excluded(self):
  298. form = IncompleteCategoryFormWithExclude(data={'name': 'some name', 'slug': 'some-slug'})
  299. assert form.is_valid()
  300. def test_notrequired_overrides_notblank(self):
  301. form = CustomWriterForm({})
  302. assert form.is_valid()
  303. # unique/unique_together validation
  304. class UniqueTest(TestCase):
  305. def setUp(self):
  306. self.writer = Writer.objects.create(name='Mike Royko')
  307. def test_simple_unique(self):
  308. form = ProductForm({'slug': 'teddy-bear-blue'})
  309. self.assertTrue(form.is_valid())
  310. obj = form.save()
  311. form = ProductForm({'slug': 'teddy-bear-blue'})
  312. self.assertEqual(len(form.errors), 1)
  313. self.assertEqual(form.errors['slug'], [u'Product with this Slug already exists.'])
  314. form = ProductForm({'slug': 'teddy-bear-blue'}, instance=obj)
  315. self.assertTrue(form.is_valid())
  316. def test_unique_together(self):
  317. """ModelForm test of unique_together constraint"""
  318. form = PriceForm({'price': '6.00', 'quantity': '1'})
  319. self.assertTrue(form.is_valid())
  320. form.save()
  321. form = PriceForm({'price': '6.00', 'quantity': '1'})
  322. self.assertFalse(form.is_valid())
  323. self.assertEqual(len(form.errors), 1)
  324. self.assertEqual(form.errors['__all__'], [u'Price with this Price and Quantity already exists.'])
  325. def test_unique_null(self):
  326. title = 'I May Be Wrong But I Doubt It'
  327. form = BookForm({'title': title, 'author': self.writer.pk})
  328. self.assertTrue(form.is_valid())
  329. form.save()
  330. form = BookForm({'title': title, 'author': self.writer.pk})
  331. self.assertFalse(form.is_valid())
  332. self.assertEqual(len(form.errors), 1)
  333. self.assertEqual(form.errors['__all__'], [u'Book with this Title and Author already exists.'])
  334. form = BookForm({'title': title})
  335. self.assertTrue(form.is_valid())
  336. form.save()
  337. form = BookForm({'title': title})
  338. self.assertTrue(form.is_valid())
  339. def test_inherited_unique(self):
  340. title = 'Boss'
  341. Book.objects.create(title=title, author=self.writer, special_id=1)
  342. form = DerivedBookForm({'title': 'Other', 'author': self.writer.pk, 'special_id': u'1', 'isbn': '12345'})
  343. self.assertFalse(form.is_valid())
  344. self.assertEqual(len(form.errors), 1)
  345. self.assertEqual(form.errors['special_id'], [u'Book with this Special id already exists.'])
  346. def test_inherited_unique_together(self):
  347. title = 'Boss'
  348. form = BookForm({'title': title, 'author': self.writer.pk})
  349. self.assertTrue(form.is_valid())
  350. form.save()
  351. form = DerivedBookForm({'title': title, 'author': self.writer.pk, 'isbn': '12345'})
  352. self.assertFalse(form.is_valid())
  353. self.assertEqual(len(form.errors), 1)
  354. self.assertEqual(form.errors['__all__'], [u'Book with this Title and Author already exists.'])
  355. def test_abstract_inherited_unique(self):
  356. title = 'Boss'
  357. isbn = '12345'
  358. dbook = DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn)
  359. form = DerivedBookForm({'title': 'Other', 'author': self.writer.pk, 'isbn': isbn})
  360. self.assertFalse(form.is_valid())
  361. self.assertEqual(len(form.errors), 1)
  362. self.assertEqual(form.errors['isbn'], [u'Derived book with this Isbn already exists.'])
  363. def test_abstract_inherited_unique_together(self):
  364. title = 'Boss'
  365. isbn = '12345'
  366. dbook = DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn)
  367. form = DerivedBookForm({
  368. 'title': 'Other',
  369. 'author': self.writer.pk,
  370. 'isbn': '9876',
  371. 'suffix1': u'0',
  372. 'suffix2': u'0'
  373. })
  374. self.assertFalse(form.is_valid())
  375. self.assertEqual(len(form.errors), 1)
  376. self.assertEqual(form.errors['__all__'],
  377. [u'Derived book with this Suffix1 and Suffix2 already exists.'])
  378. def test_explicitpk_unspecified(self):
  379. """Test for primary_key being in the form and failing validation."""
  380. form = ExplicitPKForm({'key': u'', 'desc': u'' })
  381. self.assertFalse(form.is_valid())
  382. def test_explicitpk_unique(self):
  383. """Ensure keys and blank character strings are tested for uniqueness."""
  384. form = ExplicitPKForm({'key': u'key1', 'desc': u''})
  385. self.assertTrue(form.is_valid())
  386. form.save()
  387. form = ExplicitPKForm({'key': u'key1', 'desc': u''})
  388. self.assertFalse(form.is_valid())
  389. self.assertEqual(len(form.errors), 3)
  390. self.assertEqual(form.errors['__all__'], [u'Explicit pk with this Key and Desc already exists.'])
  391. self.assertEqual(form.errors['desc'], [u'Explicit pk with this Desc already exists.'])
  392. self.assertEqual(form.errors['key'], [u'Explicit pk with this Key already exists.'])
  393. def test_unique_for_date(self):
  394. p = Post.objects.create(title="Django 1.0 is released",
  395. slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3))
  396. form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'})
  397. self.assertFalse(form.is_valid())
  398. self.assertEqual(len(form.errors), 1)
  399. self.assertEqual(form.errors['title'], [u'Title must be unique for Posted date.'])
  400. form = PostForm({'title': "Work on Django 1.1 begins", 'posted': '2008-09-03'})
  401. self.assertTrue(form.is_valid())
  402. form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-04'})
  403. self.assertTrue(form.is_valid())
  404. form = PostForm({'slug': "Django 1.0", 'posted': '2008-01-01'})
  405. self.assertFalse(form.is_valid())
  406. self.assertEqual(len(form.errors), 1)
  407. self.assertEqual(form.errors['slug'], [u'Slug must be unique for Posted year.'])
  408. form = PostForm({'subtitle': "Finally", 'posted': '2008-09-30'})
  409. self.assertFalse(form.is_valid())
  410. self.assertEqual(form.errors['subtitle'], [u'Subtitle must be unique for Posted month.'])
  411. form = PostForm({'subtitle': "Finally", "title": "Django 1.0 is released",
  412. "slug": "Django 1.0", 'posted': '2008-09-03'}, instance=p)
  413. self.assertTrue(form.is_valid())
  414. form = PostForm({'title': "Django 1.0 is released"})
  415. self.assertFalse(form.is_valid())
  416. self.assertEqual(len(form.errors), 1)
  417. self.assertEqual(form.errors['posted'], [u'This field is required.'])
  418. def test_inherited_unique_for_date(self):
  419. p = Post.objects.create(title="Django 1.0 is released",
  420. slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3))
  421. form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'})
  422. self.assertFalse(form.is_valid())
  423. self.assertEqual(len(form.errors), 1)
  424. self.assertEqual(form.errors['title'], [u'Title must be unique for Posted date.'])
  425. form = DerivedPostForm({'title': "Work on Django 1.1 begins", 'posted': '2008-09-03'})
  426. self.assertTrue(form.is_valid())
  427. form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-04'})
  428. self.assertTrue(form.is_valid())
  429. form = DerivedPostForm({'slug': "Django 1.0", 'posted': '2008-01-01'})
  430. self.assertFalse(form.is_valid())
  431. self.assertEqual(len(form.errors), 1)
  432. self.assertEqual(form.errors['slug'], [u'Slug must be unique for Posted year.'])
  433. form = DerivedPostForm({'subtitle': "Finally", 'posted': '2008-09-30'})
  434. self.assertFalse(form.is_valid())
  435. self.assertEqual(form.errors['subtitle'], [u'Subtitle must be unique for Posted month.'])
  436. form = DerivedPostForm({'subtitle': "Finally", "title": "Django 1.0 is released",
  437. "slug": "Django 1.0", 'posted': '2008-09-03'}, instance=p)
  438. self.assertTrue(form.is_valid())
  439. def test_unique_for_date_with_nullable_date(self):
  440. p = FlexibleDatePost.objects.create(title="Django 1.0 is released",
  441. slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3))
  442. form = FlexDatePostForm({'title': "Django 1.0 is released"})
  443. self.assertTrue(form.is_valid())
  444. form = FlexDatePostForm({'slug': "Django 1.0"})
  445. self.assertTrue(form.is_valid())
  446. form = FlexDatePostForm({'subtitle': "Finally"})
  447. self.assertTrue(form.is_valid())
  448. form = FlexDatePostForm({'subtitle': "Finally", "title": "Django 1.0 is released",
  449. "slug": "Django 1.0"}, instance=p)
  450. self.assertTrue(form.is_valid())
  451. class OldFormForXTests(TestCase):
  452. def test_base_form(self):
  453. self.assertEqual(Category.objects.count(), 0)
  454. f = BaseCategoryForm()
  455. self.assertHTMLEqual(
  456. str(f),
  457. """<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr>
  458. <tr><th><label for="id_slug">Slug:</label></th><td><input id="id_slug" type="text" name="slug" maxlength="20" /></td></tr>
  459. <tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr>"""
  460. )
  461. self.assertHTMLEqual(
  462. str(f.as_ul()),
  463. """<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="20" /></li>
  464. <li><label for="id_slug">Slug:</label> <input id="id_slug" type="text" name="slug" maxlength="20" /></li>
  465. <li><label for="id_url">The URL:</label> <input id="id_url" type="text" name="url" maxlength="40" /></li>"""
  466. )
  467. self.assertHTMLEqual(
  468. str(f["name"]),
  469. """<input id="id_name" type="text" name="name" maxlength="20" />""")
  470. def test_auto_id(self):
  471. f = BaseCategoryForm(auto_id=False)
  472. self.assertHTMLEqual(
  473. str(f.as_ul()),
  474. """<li>Name: <input type="text" name="name" maxlength="20" /></li>
  475. <li>Slug: <input type="text" name="slug" maxlength="20" /></li>
  476. <li>The URL: <input type="text" name="url" maxlength="40" /></li>"""
  477. )
  478. def test_with_data(self):
  479. self.assertEqual(Category.objects.count(), 0)
  480. f = BaseCategoryForm({'name': 'Entertainment',
  481. 'slug': 'entertainment',
  482. 'url': 'entertainment'})
  483. self.assertTrue(f.is_valid())
  484. self.assertEqual(f.cleaned_data['name'], 'Entertainment')
  485. self.assertEqual(f.cleaned_data['slug'], 'entertainment')
  486. self.assertEqual(f.cleaned_data['url'], 'entertainment')
  487. c1 = f.save()
  488. # Testing wether the same object is returned from the
  489. # ORM... not the fastest way...
  490. self.assertEqual(c1, Category.objects.all()[0])
  491. self.assertEqual(c1.name, "Entertainment")
  492. self.assertEqual(Category.objects.count(), 1)
  493. f = BaseCategoryForm({'name': "It's a test",
  494. 'slug': 'its-test',
  495. 'url': 'test'})
  496. self.assertTrue(f.is_valid())
  497. self.assertEqual(f.cleaned_data['name'], "It's a test")
  498. self.assertEqual(f.cleaned_data['slug'], 'its-test')
  499. self.assertEqual(f.cleaned_data['url'], 'test')
  500. c2 = f.save()
  501. # Testing wether the same object is returned from the
  502. # ORM... not the fastest way...
  503. self.assertEqual(c2, Category.objects.get(pk=c2.pk))
  504. self.assertEqual(c2.name, "It's a test")
  505. self.assertEqual(Category.objects.count(), 2)
  506. # If you call save() with commit=False, then it will return an object that
  507. # hasn't yet been saved to the database. In this case, it's up to you to call
  508. # save() on the resulting model instance.
  509. f = BaseCategoryForm({'name': 'Third test', 'slug': 'third-test', 'url': 'third'})
  510. self.assertEqual(f.is_valid(), True)
  511. self.assertEqual(f.cleaned_data['url'], u'third')
  512. self.assertEqual(f.cleaned_data['name'], u'Third test')
  513. self.assertEqual(f.cleaned_data['slug'], u'third-test')
  514. c3 = f.save(commit=False)
  515. self.assertEqual(c3.name, "Third test")
  516. self.assertEqual(Category.objects.count(), 2)
  517. c3.save()
  518. self.assertEqual(Category.objects.count(), 3)
  519. # If you call save() with invalid data, you'll get a ValueError.
  520. f = BaseCategoryForm({'name': '', 'slug': 'not a slug!', 'url': 'foo'})
  521. self.assertEqual(f.errors['name'], [u'This field is required.'])
  522. self.assertEqual(f.errors['slug'], [u"Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."])
  523. with self.assertRaises(AttributeError):
  524. f.cleaned_data
  525. with self.assertRaises(ValueError):
  526. f.save()
  527. f = BaseCategoryForm({'name': '', 'slug': '', 'url': 'foo'})
  528. with self.assertRaises(ValueError):
  529. f.save()
  530. # Create a couple of Writers.
  531. w_royko = Writer(name='Mike Royko')
  532. w_royko.save()
  533. w_woodward = Writer(name='Bob Woodward')
  534. w_woodward.save()
  535. # ManyToManyFields are represented by a MultipleChoiceField, ForeignKeys and any
  536. # fields with the 'choices' attribute are represented by a ChoiceField.
  537. f = ArticleForm(auto_id=False)
  538. self.assertHTMLEqual(unicode(f), '''<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" /></td></tr>
  539. <tr><th>Slug:</th><td><input type="text" name="slug" maxlength="50" /></td></tr>
  540. <tr><th>Pub date:</th><td><input type="text" name="pub_date" /></td></tr>
  541. <tr><th>Writer:</th><td><select name="writer">
  542. <option value="" selected="selected">---------</option>
  543. <option value="%s">Bob Woodward</option>
  544. <option value="%s">Mike Royko</option>
  545. </select></td></tr>
  546. <tr><th>Article:</th><td><textarea rows="10" cols="40" name="article"></textarea></td></tr>
  547. <tr><th>Categories:</th><td><select multiple="multiple" name="categories">
  548. <option value="%s">Entertainment</option>
  549. <option value="%s">It&#39;s a test</option>
  550. <option value="%s">Third test</option>
  551. </select><br /><span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></td></tr>
  552. <tr><th>Status:</th><td><select name="status">
  553. <option value="" selected="selected">---------</option>
  554. <option value="1">Draft</option>
  555. <option value="2">Pending</option>
  556. <option value="3">Live</option>
  557. </select></td></tr>''' % (w_woodward.pk, w_royko.pk, c1.pk, c2.pk, c3.pk))
  558. # You can restrict a form to a subset of the complete list of fields
  559. # by providing a 'fields' argument. If you try to save a
  560. # model created with such a form, you need to ensure that the fields
  561. # that are _not_ on the form have default values, or are allowed to have
  562. # a value of None. If a field isn't specified on a form, the object created
  563. # from the form can't provide a value for that field!
  564. f = PartialArticleForm(auto_id=False)
  565. self.assertHTMLEqual(unicode(f), '''<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" /></td></tr>
  566. <tr><th>Pub date:</th><td><input type="text" name="pub_date" /></td></tr>''')
  567. # When the ModelForm is passed an instance, that instance's current values are
  568. # inserted as 'initial' data in each Field.
  569. w = Writer.objects.get(name='Mike Royko')
  570. f = RoykoForm(auto_id=False, instance=w)
  571. self.assertHTMLEqual(unicode(f), '''<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>''')
  572. art = Article(
  573. headline='Test article',
  574. slug='test-article',
  575. pub_date=datetime.date(1988, 1, 4),
  576. writer=w,
  577. article='Hello.'
  578. )
  579. art.save()
  580. art_id_1 = art.id
  581. self.assertEqual(art_id_1 is not None, True)
  582. f = TestArticleForm(auto_id=False, instance=art)
  583. self.assertHTMLEqual(f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="Test article" maxlength="50" /></li>
  584. <li>Slug: <input type="text" name="slug" value="test-article" maxlength="50" /></li>
  585. <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" /></li>
  586. <li>Writer: <select name="writer">
  587. <option value="">---------</option>
  588. <option value="%s">Bob Woodward</option>
  589. <option value="%s" selected="selected">Mike Royko</option>
  590. </select></li>
  591. <li>Article: <textarea rows="10" cols="40" name="article">Hello.</textarea></li>
  592. <li>Categories: <select multiple="multiple" name="categories">
  593. <option value="%s">Entertainment</option>
  594. <option value="%s">It&#39;s a test</option>
  595. <option value="%s">Third test</option>
  596. </select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>
  597. <li>Status: <select name="status">
  598. <option value="" selected="selected">---------</option>
  599. <option value="1">Draft</option>
  600. <option value="2">Pending</option>
  601. <option value="3">Live</option>
  602. </select></li>''' % (w_woodward.pk, w_royko.pk, c1.pk, c2.pk, c3.pk))
  603. f = TestArticleForm({
  604. 'headline': u'Test headline',
  605. 'slug': 'test-headline',
  606. 'pub_date': u'1984-02-06',
  607. 'writer': unicode(w_royko.pk),
  608. 'article': 'Hello.'
  609. }, instance=art)
  610. self.assertEqual(f.errors, {})
  611. self.assertEqual(f.is_valid(), True)
  612. test_art = f.save()
  613. self.assertEqual(test_art.id == art_id_1, True)
  614. test_art = Article.objects.get(id=art_id_1)
  615. self.assertEqual(test_art.headline, u'Test headline')
  616. # You can create a form over a subset of the available fields
  617. # by specifying a 'fields' argument to form_for_instance.
  618. f = PartialArticleFormWithSlug({
  619. 'headline': u'New headline',
  620. 'slug': 'new-headline',
  621. 'pub_date': u'1988-01-04'
  622. }, auto_id=False, instance=art)
  623. self.assertHTMLEqual(f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" /></li>
  624. <li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" /></li>
  625. <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" /></li>''')
  626. self.assertEqual(f.is_valid(), True)
  627. new_art = f.save()
  628. self.assertEqual(new_art.id == art_id_1, True)
  629. new_art = Article.objects.get(id=art_id_1)
  630. self.assertEqual(new_art.headline, u'New headline')
  631. # Add some categories and test the many-to-many form output.
  632. self.assertEqual(map(lambda o: o.name, new_art.categories.all()), [])
  633. new_art.categories.add(Category.objects.get(name='Entertainment'))
  634. self.assertEqual(map(lambda o: o.name, new_art.categories.all()), ["Entertainment"])
  635. f = TestArticleForm(auto_id=False, instance=new_art)
  636. self.assertHTMLEqual(f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" /></li>
  637. <li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" /></li>
  638. <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" /></li>
  639. <li>Writer: <select name="writer">
  640. <option value="">---------</option>
  641. <option value="%s">Bob Woodward</option>
  642. <option value="%s" selected="selected">Mike Royko</option>
  643. </select></li>
  644. <li>Article: <textarea rows="10" cols="40" name="article">Hello.</textarea></li>
  645. <li>Categories: <select multiple="multiple" name="categories">
  646. <option value="%s" selected="selected">Entertainment</option>
  647. <option value="%s">It&#39;s a test</option>
  648. <option value="%s">Third test</option>
  649. </select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>
  650. <li>Status: <select name="status">
  651. <option value="" selected="selected">---------</option>
  652. <option value="1">Draft</option>
  653. <option value="2">Pending</option>
  654. <option value="3">Live</option>
  655. </select></li>''' % (w_woodward.pk, w_royko.pk, c1.pk, c2.pk, c3.pk))
  656. # Initial values can be provided for model forms
  657. f = TestArticleForm(
  658. auto_id=False,
  659. initial={
  660. 'headline': 'Your headline here',
  661. 'categories': [str(c1.id), str(c2.id)]
  662. })
  663. self.assertHTMLEqual(f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="Your headline here" maxlength="50" /></li>
  664. <li>Slug: <input type="text" name="slug" maxlength="50" /></li>
  665. <li>Pub date: <input type="text" name="pub_date" /></li>
  666. <li>Writer: <select name="writer">
  667. <option value="" selected="selected">---------</option>
  668. <option value="%s">Bob Woodward</option>
  669. <option value="%s">Mike Royko</option>
  670. </select></li>
  671. <li>Article: <textarea rows="10" cols="40" name="article"></textarea></li>
  672. <li>Categories: <select multiple="multiple" name="categories">
  673. <option value="%s" selected="selected">Entertainment</option>
  674. <option value="%s" selected="selected">It&#39;s a test</option>
  675. <option value="%s">Third test</option>
  676. </select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>
  677. <li>Status: <select name="status">
  678. <option value="" selected="selected">---------</option>
  679. <option value="1">Draft</option>
  680. <option value="2">Pending</option>
  681. <option value="3">Live</option>
  682. </select></li>''' % (w_woodward.pk, w_royko.pk, c1.pk, c2.pk, c3.pk))
  683. f = TestArticleForm({
  684. 'headline': u'New headline',
  685. 'slug': u'new-headline',
  686. 'pub_date': u'1988-01-04',
  687. 'writer': unicode(w_royko.pk),
  688. 'article': u'Hello.',
  689. 'categories': [unicode(c1.id), unicode(c2.id)]
  690. }, instance=new_art)
  691. new_art = f.save()
  692. self.assertEqual(new_art.id == art_id_1, True)
  693. new_art = Article.objects.get(id=art_id_1)
  694. self.assertEqual(map(lambda o: o.name, new_art.categories.order_by('name')),
  695. ["Entertainment", "It's a test"])
  696. # Now, submit form data with no categories. This deletes the existing categories.
  697. f = TestArticleForm({'headline': u'New headline', 'slug': u'new-headline', 'pub_date': u'1988-01-04',
  698. 'writer': unicode(w_royko.pk), 'article': u'Hello.'}, instance=new_art)
  699. new_art = f.save()
  700. self.assertEqual(new_art.id == art_id_1, True)
  701. new_art = Article.objects.get(id=art_id_1)
  702. self.assertEqual(map(lambda o: o.name, new_art.categories.all()), [])
  703. # Create a new article, with categories, via the form.
  704. f = ArticleForm({'headline': u'The walrus was Paul', 'slug': u'walrus-was-paul', 'pub_date': u'1967-11-01',
  705. 'writer': unicode(w_royko.pk), 'article': u'Test.', 'categories': [unicode(c1.id), unicode(c2.id)]})
  706. new_art = f.save()
  707. art_id_2 = new_art.id
  708. self.assertEqual(art_id_2 not in (None, art_id_1), True)
  709. new_art = Article.objects.get(id=art_id_2)
  710. self.assertEqual(map(lambda o: o.name, new_art.categories.order_by('name')), ["Entertainment", "It's a test"])
  711. # Create a new article, with no categories, via the form.
  712. f = ArticleForm({'headline': u'The walrus was Paul', 'slug': u'walrus-was-paul', 'pub_date': u'1967-11-01',
  713. 'writer': unicode(w_royko.pk), 'article': u'Test.'})
  714. new_art = f.save()
  715. art_id_3 = new_art.id
  716. self.assertEqual(art_id_3 not in (None, art_id_1, art_id_2), True)
  717. new_art = Article.objects.get(id=art_id_3)
  718. self.assertEqual(map(lambda o: o.name, new_art.categories.all()), [])
  719. # Create a new article, with categories, via the form, but use commit=False.
  720. # The m2m data won't be saved until save_m2m() is invoked on the form.
  721. f = ArticleForm({'headline': u'The walrus was Paul', 'slug': 'walrus-was-paul', 'pub_date': u'1967-11-01',
  722. 'writer': unicode(w_royko.pk), 'article': u'Test.', 'categories': [unicode(c1.id), unicode(c2.id)]})
  723. new_art = f.save(commit=False)
  724. # Manually save the instance
  725. new_art.save()
  726. art_id_4 = new_art.id
  727. self.assertEqual(art_id_4 not in (None, art_id_1, art_id_2, art_id_3), True)
  728. # The instance doesn't have m2m data yet
  729. new_art = Article.objects.get(id=art_id_4)
  730. self.assertEqual(map(lambda o: o.name, new_art.categories.all()), [])
  731. # Save the m2m data on the form
  732. f.save_m2m()
  733. self.assertEqual(map(lambda o: o.name, new_art.categories.order_by('name')), ["Entertainment", "It's a test"])
  734. # Here, we define a custom ModelForm. Because it happens to have the same fields as
  735. # the Category model, we can just call the form's save() to apply its changes to an
  736. # existing Category instance.
  737. cat = Category.objects.get(name='Third test')
  738. self.assertEqual(cat.name, "Third test")
  739. self.assertEqual(cat.id == c3.id, True)
  740. form = ShortCategory({'name': 'Third', 'slug': 'third', 'url': '3rd'}, instance=cat)
  741. self.assertEqual(form.save().name, 'Third')
  742. self.assertEqual(Category.objects.get(id=c3.id).name, 'Third')
  743. # Here, we demonstrate that choices for a ForeignKey ChoiceField are determined
  744. # at runtime, based on the data in the database when the form is displayed, not
  745. # the data in the database when the form is instantiated.
  746. f = ArticleForm(auto_id=False)
  747. self.assertHTMLEqual(f.as_ul(), '''<li>Headline: <input type="text" name="headline" maxlength="50" /></li>
  748. <li>Slug: <input type="text" name="slug" maxlength="50" /></li>
  749. <li>Pub date: <input type="text" name="pub_date" /></li>
  750. <li>Writer: <select name="writer">
  751. <option value="" selected="selected">---------</option>
  752. <option value="%s">Bob Woodward</option>
  753. <option value="%s">Mike Royko</option>
  754. </select></li>
  755. <li>Article: <textarea rows="10" cols="40" name="article"></textarea></li>
  756. <li>Categories: <select multiple="multiple" name="categories">
  757. <option value="%s">Entertainment</option>
  758. <option value="%s">It&#39;s a test</option>
  759. <option value="%s">Third</option>
  760. </select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>
  761. <li>Status: <select name="status">
  762. <option value="" selected="selected">---------</option>
  763. <option value="1">Draft</option>
  764. <option value="2">Pending</option>
  765. <option value="3">Live</option>
  766. </select></li>''' % (w_woodward.pk, w_royko.pk, c1.pk, c2.pk, c3.pk))
  767. c4 = Category.objects.create(name='Fourth', url='4th')
  768. self.assertEqual(c4.name, 'Fourth')
  769. w_bernstein = Writer.objects.create(name='Carl Bernstein')
  770. self.assertEqual(w_bernstein.name, 'Carl Bernstein')
  771. self.assertHTMLEqual(f.as_ul(), '''<li>Headline: <input type="text" name="headline" maxlength="50" /></li>
  772. <li>Slug: <input type="text" name="slug" maxlength="50" /></li>
  773. <li>Pub date: <input type="text" name="pub_date" /></li>
  774. <li>Writer: <select name="writer">
  775. <option value="" selected="selected">---------</option>
  776. <option value="%s">Bob Woodward</option>
  777. <option value="%s">Carl Bernstein</option>
  778. <option value="%s">Mike Royko</option>
  779. </select></li>
  780. <li>Article: <textarea rows="10" cols="40" name="article"></textarea></li>
  781. <li>Categories: <select multiple="multiple" name="categories">
  782. <option value="%s">Entertainment</option>
  783. <option value="%s">It&#39;s a test</option>
  784. <option value="%s">Third</option>
  785. <option value="%s">Fourth</option>
  786. </select> <span class="helptext"> Hold down "Control", or "Command" on a Mac, to select more than one.</span></li>
  787. <li>Status: <select name="status">
  788. <option value="" selected="selected">---------</option>
  789. <option value="1">Draft</option>
  790. <option value="2">Pending</option>
  791. <option value="3">Live</option>
  792. </select></li>''' % (w_woodward.pk, w_bernstein.pk, w_royko.pk, c1.pk, c2.pk, c3.pk, c4.pk))
  793. # ModelChoiceField ############################################################
  794. f = forms.ModelChoiceField(Category.objects.all())
  795. self.assertEqual(list(f.choices), [
  796. (u'', u'---------'),
  797. (c1.pk, u'Entertainment'),
  798. (c2.pk, u"It's a test"),
  799. (c3.pk, u'Third'),
  800. (c4.pk, u'Fourth')])
  801. with self.assertRaises(ValidationError):
  802. f.clean('')
  803. with self.assertRaises(ValidationError):
  804. f.clean(None)
  805. with self.assertRaises(ValidationError):
  806. f.clean(0)
  807. self.assertEqual(f.clean(c3.id).name, 'Third')
  808. self.assertEqual(f.clean(c2.id).name, "It's a test")
  809. # Add a Category object *after* the ModelChoiceField has already been
  810. # instantiated. This proves clean() checks the database during clean() rather
  811. # than caching it at time of instantiation.
  812. c5 = Category.objects.create(name='Fifth', url='5th')
  813. self.assertEqual(c5.name, 'Fifth')
  814. self.assertEqual(f.clean(c5.id).name, 'Fifth')
  815. # Delete a Category object *after* the ModelChoiceField has already been
  816. # instantiated. This proves clean() checks the database during clean() rather
  817. # than caching it at time of instantiation.
  818. Category.objects.get(url='5th').delete()
  819. with self.assertRaises(ValidationError):
  820. f.clean(c5.id)
  821. f = forms.ModelChoiceField(Category.objects.filter(pk=c1.id), required=False)
  822. self.assertEqual(f.clean(''), None)
  823. f.clean('')
  824. self.assertEqual(f.clean(str(c1.id)).name, "Entertainment")
  825. with self.assertRaises(ValidationError):
  826. f.clean('100')
  827. # queryset can be changed after the field is created.
  828. f.queryset = Category.objects.exclude(name='Fourth')
  829. self.assertEqual(list(f.choices), [
  830. (u'', u'---------'),
  831. (c1.pk, u'Entertainment'),
  832. (c2.pk, u"It's a test"),
  833. (c3.pk, u'Third')])
  834. self.assertEqual(f.clean(c3.id).name, 'Third')
  835. with self.assertRaises(ValidationError):
  836. f.clean(c4.id)
  837. # check that we can safely iterate choices repeatedly
  838. gen_one = list(f.choices)
  839. gen_two = f.choices
  840. self.assertEqual(gen_one[2], (c2.pk, u"It's a test"))
  841. self.assertEqual(list(gen_two), [
  842. (u'', u'---------'),
  843. (c1.pk, u'Entertainment'),
  844. (c2.pk, u"It's a test"),
  845. (c3.pk, u'Third')])
  846. # check that we can override the label_from_instance method to print custom labels (#4620)
  847. f.queryset = Category.objects.all()
  848. f.label_from_instance = lambda obj: "category " + str(obj)
  849. self.assertEqual(list(f.choices), [
  850. (u'', u'---------'),
  851. (c1.pk, 'category Entertainment'),
  852. (c2.pk, "category It's a test"),
  853. (c3.pk, 'category Third'),
  854. (c4.pk, 'category Fourth')])
  855. # ModelMultipleChoiceField ####################################################
  856. f = forms.ModelMultipleChoiceField(Category.objects.all())
  857. self.assertEqual(list(f.choices), [
  858. (c1.pk, u'Entertainment'),
  859. (c2.pk, u"It's a test"),
  860. (c3.pk, u'Third'),
  861. (c4.pk, u'Fourth')])
  862. with self.assertRaises(ValidationError):
  863. f.clean(None)
  864. with self.assertRaises(ValidationError):
  865. f.clean([])
  866. self.assertEqual(map(lambda o: o.name, f.clean([c1.id])), ["Entertainment"])
  867. self.assertEqual(map(lambda o: o.name, f.clean([c2.id])), ["It's a test"])
  868. self.assertEqual(map(lambda o: o.name, f.clean([str(c1.id)])), ["Entertainment"])
  869. self.assertEqual(map(lambda o: o.name, f.clean([str(c1.id), str(c2.id)])), ["Entertainment", "It's a test"])
  870. self.assertEqual(map(lambda o: o.name, f.clean([c1.id, str(c2.id)])), ["Entertainment", "It's a test"])
  871. self.assertEqual(map(lambda o: o.name, f.clean((c1.id, str(c2.id)))), ["Entertainment", "It's a test"])
  872. with self.assertRaises(ValidationError):
  873. f.clean(['100'])
  874. with self.assertRaises(ValidationError):
  875. f.clean('hello')
  876. with self.assertRaises(ValidationError):
  877. f.clean(['fail'])
  878. # Add a Category object *after* the ModelMultipleChoiceField has already been
  879. # instantiated. This proves clean() checks the database during clean() rather
  880. # than caching it at time of instantiation.
  881. c6 = Category.objects.create(id=6, name='Sixth', url='6th')
  882. self.assertEqual(c6.name, 'Sixth')
  883. self.assertEqual(map(lambda o: o.name, f.clean([c6.id])), ["Sixth"])
  884. # Delete a Category object *after* the ModelMultipleChoiceField has already been
  885. # instantiated. This proves clean() checks the database during clean() rather
  886. # than caching it at time of instantiation.
  887. Category.objects.get(url='6th').delete()
  888. with self.assertRaises(ValidationError):
  889. f.clean([c6.id])
  890. f = forms.ModelMultipleChoiceField(Category.objects.all(), required=False)
  891. self.assertEqual(f.clean([]), [])
  892. self.assertEqual(f.clean(()), [])
  893. with self.assertRaises(ValidationError):
  894. f.clean(['10'])
  895. with self.assertRaises(ValidationError):
  896. f.clean([str(c3.id), '10'])
  897. with self.assertRaises(ValidationError):
  898. f.clean([str(c1.id), '10'])
  899. # queryset can be changed after the field is created.
  900. f.queryset = Category.objects.exclude(name='Fourth')
  901. self.assertEqual(list(f.choices), [
  902. (c1.pk, u'Entertainment'),
  903. (c2.pk, u"It's a test"),
  904. (c3.pk, u'Third')])
  905. self.assertEqual(map(lambda o: o.name, f.clean([c3.id])), ["Third"])
  906. with self.assertRaises(ValidationError):
  907. f.clean([c4.id])
  908. with self.assertRaises(ValidationError):
  909. f.clean([str(c3.id), str(c4.id)])
  910. f.queryset = Category.objects.all()
  911. f.label_from_instance = lambda obj: "multicategory " + str(obj)
  912. self.assertEqual(list(f.choices), [
  913. (c1.pk, 'multicategory Entertainment'),
  914. (c2.pk, "multicategory It's a test"),
  915. (c3.pk, 'multicategory Third'),
  916. (c4.pk, 'multicategory Fourth')])
  917. # OneToOneField ###############################################################
  918. self.assertEqual(ImprovedArticleForm.base_fields.keys(), ['article'])
  919. self.assertEqual(ImprovedArticleWithParentLinkForm.base_fields.keys(), [])
  920. bw = BetterWriter(name=u'Joe Better', score=10)
  921. bw.save()
  922. self.assertEqual(sorted(model_to_dict(bw).keys()),
  923. ['id', 'name', 'score', 'writer_ptr'])
  924. form = BetterWriterForm({'name': 'Some Name', 'score': 12})
  925. self.assertEqual(form.is_valid(), True)
  926. bw2 = form.save()
  927. bw2.delete()
  928. form = WriterProfileForm()
  929. self.assertHTMLEqual(form.as_p(), '''<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer">
  930. <option value="" selected="selected">---------</option>
  931. <option value="%s">Bob Woodward</option>
  932. <option value="%s">Carl Bernstein</option>
  933. <option value="%s">Joe Better</option>
  934. <option value="%s">Mike Royko</option>
  935. </select></p>
  936. <p><label for="id_age">Age:</label> <input type="text" name="age" id="id_age" /></p>''' % (w_woodward.pk, w_bernstein.pk, bw.pk, w_royko.pk))
  937. data = {
  938. 'writer': unicode(w_woodward.pk),
  939. 'age': u'65',
  940. }
  941. form = WriterProfileForm(data)
  942. instance = form.save()
  943. self.assertEqual(unicode(instance), 'Bob Woodward is 65')
  944. form = WriterProfileForm(instance=instance)
  945. self.assertHTMLEqual(form.as_p(), '''<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer">
  946. <option value="">---------</option>
  947. <option value="%s" selected="selected">Bob Woodward</option>
  948. <option value="%s">Carl Bernstein</option>
  949. <option value="%s">Joe Better</option>
  950. <option value="%s">Mike Royko</option>
  951. </select></p>
  952. <p><label for="id_age">Age:</label> <input type="text" name="age" value="65" id="id_age" /></p>''' % (w_woodward.pk, w_bernstein.pk, bw.pk, w_royko.pk))
  953. def test_phone_number_field(self):
  954. f = PhoneNumberForm({'phone': '(312) 555-1212', 'description': 'Assistance'})
  955. self.assertEqual(f.is_valid(), True)
  956. self.assertEqual(f.cleaned_data['phone'], u'312-555-1212')
  957. self.assertEqual(f.cleaned_data['description'], u'Assistance')
  958. def test_file_field(self):
  959. # Test conditions when files is either not given or empty.
  960. f = TextFileForm(data={'description': u'Assistance'})
  961. self.assertEqual(f.is_valid(), False)
  962. f = TextFileForm(data={'description': u'Assistance'}, files={})
  963. self.assertEqual(f.is_valid(), False)
  964. # Upload a file and ensure it all works as expected.
  965. f = TextFileForm(
  966. data={'description': u'Assistance'},
  967. files={'file': SimpleUploadedFile('test1.txt', 'hello world')})
  968. self.assertEqual(f.is_valid(), True)
  969. self.assertEqual(type(f.cleaned_data['file']), SimpleUploadedFile)
  970. instance = f.save()
  971. self.assertEqual(instance.file.name, 'tests/test1.txt')
  972. instance.file.delete()
  973. f = TextFileForm(
  974. data={'description': u'Assistance'},
  975. files={'file': SimpleUploadedFile('test1.txt', 'hello world')})
  976. self.assertEqual(f.is_valid(), True)
  977. self.assertEqual(type(f.cleaned_data['file']), SimpleUploadedFile)
  978. instance = f.save()
  979. self.assertEqual(instance.file.name, 'tests/test1.txt')
  980. # Check if the max_length attribute has been inherited from the model.
  981. f = TextFileForm(
  982. data={'description': u'Assistance'},
  983. files={'file': SimpleUploadedFile('test-maxlength.txt', 'hello world')})
  984. self.assertEqual(f.is_valid(), False)
  985. # Edit an instance that already has the file defined in the model. This will not
  986. # save the file again, but leave it exactly as it is.
  987. f = TextFileForm(
  988. data={'description': u'Assistance'},
  989. instance=instance)
  990. self.assertEqual(f.is_valid(), True)
  991. self.assertEqual(f.cleaned_data['file'].name, 'tests/test1.txt')
  992. instance = f.save()
  993. self.assertEqual(instance.file.name, 'tests/test1.txt')
  994. # Delete the current file since this is not done by Django.
  995. instance.file.delete()
  996. # Override the file by uploading a new one.
  997. f = TextFileForm(
  998. data={'description': u'Assistance'},
  999. files={'file': SimpleUploadedFile('test2.txt', 'hello world')}, instance=instance)
  1000. self.assertEqual(f.is_valid(), True)
  1001. instance = f.save()
  1002. self.assertEqual(instance.file.name, 'tests/test2.txt')
  1003. # Delete the current file since this is not done by Django.
  1004. instance.file.delete()
  1005. f = TextFileForm(
  1006. data={'description': u'Assistance'},
  1007. files={'file': SimpleUploadedFile('test2.txt', 'hello world')})
  1008. self.assertEqual(f.is_valid(), True)
  1009. instance = f.save()
  1010. self.assertEqual(instance.file.name, 'tests/test2.txt')
  1011. # Delete the current file since this is not done by Django.
  1012. instance.file.delete()
  1013. instance.delete()
  1014. # Test the non-required FileField
  1015. f = TextFileForm(data={'description': u'Assistance'})
  1016. f.fields['file'].required = False
  1017. self.assertEqual(f.is_valid(), True)
  1018. instance = f.save()
  1019. self.assertEqual(instance.file.name, '')
  1020. f = TextFileForm(
  1021. data={'description': u'Assistance'},
  1022. files={'file': SimpleUploadedFile('test3.txt', 'hello world')}, instance=instance)
  1023. self.assertEqual(f.is_valid(), True)
  1024. instance = f.save()
  1025. self.assertEqual(instance.file.name, 'tests/test3.txt')
  1026. # Instance can be edited w/out re-uploading the file and existing file should be preserved.
  1027. f = TextFileForm(
  1028. data={'description': u'New Description'},
  1029. instance=instance)
  1030. f.fields['file'].required = False
  1031. self.assertEqual(f.is_valid(), True)
  1032. instance = f.save()
  1033. self.assertEqual(instance.description, u'New Description')
  1034. self.assertEqual(instance.file.name, 'tests/test3.txt')
  1035. # Delete the current file since this is not done by Django.
  1036. instance.file.delete()
  1037. instance.delete()
  1038. f = TextFileForm(
  1039. data={'description': u'Assistance'},
  1040. files={'file': SimpleUploadedFile('test3.txt', 'hello world')})
  1041. self.assertEqual(f.is_valid(), True)
  1042. instance = f.save()
  1043. self.assertEqual(instance.file.name, 'tests/test3.txt')
  1044. # Delete the current file since this is not done by Django.
  1045. instance.file.delete()
  1046. instance.delete()
  1047. def test_big_integer_field(self):
  1048. bif = BigIntForm({'biggie': '-9223372036854775808'})
  1049. self.assertEqual(bif.is_valid(), True)
  1050. bif = BigIntForm({'biggie': '-9223372036854775809'})
  1051. self.assertEqual(bif.is_valid(), False)
  1052. self.assertEqual(bif.errors, {'biggie': [u'Ensure this value is greater than or equal to -9223372036854775808.']})
  1053. bif = BigIntForm({'biggie': '9223372036854775807'})
  1054. self.assertEqual(bif.is_valid(), True)
  1055. bif = BigIntForm({'biggie': '9223372036854775808'})
  1056. self.assertEqual(bif.is_valid(), False)
  1057. self.assertEqual(bif.errors, {'biggie': [u'Ensure this value is less than or equal to 9223372036854775807.']})
  1058. @skipUnless(test_images, "PIL not installed")
  1059. def test_image_field(self):
  1060. # ImageField and FileField are nearly identical, but they differ slighty when
  1061. # it comes to validation. This specifically tests that #6302 is fixed for
  1062. # both file fields and image fields.
  1063. with open(os.path.join(os.path.dirname(__file__), "test.png"), 'rb') as fp:
  1064. image_data = fp.read()
  1065. with open(os.path.join(os.path.dirname(__file__), "test2.png"), 'rb') as fp:
  1066. image_data2 = fp.read()
  1067. f = ImageFileForm(
  1068. data={'description': u'An image'},
  1069. files={'image': SimpleUploadedFile('test.png', image_data)})
  1070. self.assertEqual(f.is_valid(), True)
  1071. self.assertEqual(type(f.cleaned_data['image']), SimpleUploadedFile)
  1072. instance = f.save()
  1073. self.assertEqual(instance.image.name, 'tests/test.png')
  1074. self.assertEqual(instance.width, 16)
  1075. self.assertEqual(instance.height, 16)
  1076. # Delete the current file since this is not done by Django, but don't save
  1077. # because the dimension fields are not null=True.
  1078. instance.image.delete(save=False)
  1079. f = ImageFileForm(
  1080. data={'description': u'An image'},
  1081. files={'image': SimpleUploadedFile('test.png', image_data)})
  1082. self.assertEqual(f.is_valid(), True)
  1083. self.assertEqual(type(f.cleaned_data['image']), SimpleUploadedFile)
  1084. instance = f.save()
  1085. self.assertEqual(instance.image.name, 'tests/test.png')
  1086. self.assertEqual(instance.width, 16)
  1087. self.assertEqual(instance.height, 16)
  1088. # Edit an instance that already has the (required) image defined in the model. This will not
  1089. # save the image again, but leave it exactly as it is.
  1090. f = ImageFileForm(data={'description': u'Look, it changed'}, instance=instance)
  1091. self.assertEqual(f.is_valid(), True)
  1092. self.assertEqual(f.cleaned_data['image'].name, 'tests/test.png')
  1093. instance = f.save()
  1094. self.assertEqual(instance.image.name, 'tests/test.png')
  1095. self.assertEqual(instance.height, 16)
  1096. self.assertEqual(instance.width, 16)
  1097. # Delete the current file since this is not done by Django, but don't save
  1098. # because the dimension fields are not null=True.
  1099. instance.image.delete(save=False)
  1100. # Override the file by uploading a new one.
  1101. f = ImageFileForm(
  1102. data={'description': u'Changed it'},
  1103. files={'image': SimpleUploadedFile('test2.png', image_data2)}, instance=instance)
  1104. self.assertEqual(f.is_valid(), True)
  1105. instance = f.save()
  1106. self.assertEqual(instance.image.name, 'tests/test2.png')
  1107. self.assertEqual(instance.height, 32)
  1108. self.assertEqual(instance.width, 48)
  1109. # Delete the current file since this is not done by Django, but don't save
  1110. # because the dimension fields are not null=True.
  1111. instance.image.delete(save=False)
  1112. instance.delete()
  1113. f = ImageFileForm(
  1114. data={'description': u'Changed it'},
  1115. files={'image': SimpleUploadedFile('test2.png', image_data2)})
  1116. self.assertEqual(f.is_valid(), True)
  1117. instance = f.save()
  1118. self.assertEqual(instance.image.name, 'tests/test2.png')
  1119. self.assertEqual(instance.height, 32)
  1120. self.assertEqual(instance.width, 48)
  1121. # Delete the current file since this is not done by Django, but don't save
  1122. # because the dimension fields are not null=True.
  1123. instance.image.delete(save=False)
  1124. instance.delete()
  1125. # Test the non-required ImageField
  1126. # Note: In Oracle, we expect a null ImageField to return u'' instead of
  1127. # None.
  1128. if connection.features.interprets_empty_strings_as_nulls:
  1129. expected_null_imagefield_repr = u''
  1130. else:
  1131. expected_null_imagefield_repr = None
  1132. f = OptionalImageFileForm(data={'description': u'Test'})
  1133. self.assertEqual(f.is_valid(), True)
  1134. instance = f.save()
  1135. self.assertEqual(instance.image.name, expected_null_imagefield_repr)
  1136. self.assertEqual(instance.width, None)
  1137. self.assertEqual(instance.height, None)
  1138. f = OptionalImageFileForm(
  1139. data={'description': u'And a final one'},
  1140. files={'image': SimpleUploadedFile('test3.png', image_data)}, instance=instance)
  1141. self.assertEqual(f.is_valid(), True)
  1142. instance = f.save()
  1143. self.assertEqual(instance.image.name, 'tests/test3.png')
  1144. self.assertEqual(instance.width, 16)
  1145. self.assertEqual(instance.height, 16)
  1146. # Editing the instance without re-uploading the image should not affect the image or its width/height properties
  1147. f = OptionalImageFileForm(
  1148. data={'description': u'New Description'},
  1149. instance=instance)
  1150. self.assertEqual(f.is_valid(), True)
  1151. instance = f.save()
  1152. self.assertEqual(instance.description, u'New Description')
  1153. self.assertEqual(instance.image.name, 'tests/test3.png')
  1154. self.assertEqual(instance.width, 16)
  1155. self.assertEqual(instance.height, 16)
  1156. # Delete the current file since this is not done by Django.
  1157. instance.image.delete()
  1158. instance.delete()
  1159. f = OptionalImageFileForm(
  1160. data={'description': u'And a final one'},
  1161. files={'image': SimpleUploadedFile('test4.png', image_data2)}
  1162. )
  1163. self.assertEqual(f.is_valid(), True)
  1164. instance = f.save()
  1165. self.assertEqual(instance.image.name, 'tests/test4.png')
  1166. self.assertEqual(instance.width, 48)
  1167. self.assertEqual(instance.height, 32)
  1168. instance.delete()
  1169. # Test callable upload_to behavior that's dependent on the value of another field in the model
  1170. f = ImageFileForm(
  1171. data={'description': u'And a final one', 'path': 'foo'},
  1172. files={'image': SimpleUploadedFile('test4.png', image_data)})
  1173. self.assertEqual(f.is_valid(), True)
  1174. instance = f.save()
  1175. self.assertEqual(instance.image.name, 'foo/test4.png')
  1176. instance.delete()
  1177. def test_media_on_modelform(self):
  1178. # Similar to a regular Form class you can define custom media to be used on
  1179. # the ModelForm.
  1180. f = ModelFormWithMedia()
  1181. self.assertHTMLEqual(unicode(f.media), '''<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />
  1182. <script type="text/javascript" src="/some/form/javascript"></script>''')
  1183. f = CommaSeparatedIntegerForm({'field': '1,2,3'})
  1184. self.assertEqual(f.is_valid(), True)
  1185. self.assertEqual(f.cleaned_data, {'field': u'1,2,3'})
  1186. f = CommaSeparatedIntegerForm({'field': '1a,2'})
  1187. self.assertEqual(f.errors, {'field': [u'Enter only digits separated by commas.']})
  1188. f = CommaSeparatedIntegerForm({'field': ',,,,'})
  1189. self.assertEqual(f.is_valid(), True)
  1190. self.assertEqual(f.cleaned_data, {'field': u',,,,'})
  1191. f = CommaSeparatedIntegerForm({'field': '1.2'})
  1192. self.assertEqual(f.errors, {'field': [u'Enter only digits separated by commas.']})
  1193. f = CommaSeparatedIntegerForm({'field': '1,a,2'})
  1194. self.assertEqual(f.errors, {'field': [u'Enter only digits separated by commas.']})
  1195. f = CommaSeparatedIntegerForm({'field': '1,,2'})
  1196. self.assertEqual(f.is_valid(), True)
  1197. self.assertEqual(f.cleaned_data, {'field': u'1,,2'})
  1198. f = CommaSeparatedIntegerForm({'field': '1'})
  1199. self.assertEqual(f.is_valid(), True)
  1200. self.assertEqual(f.cleaned_data, {'field': u'1'})
  1201. # This Price instance generated by this form is not valid because the quantity
  1202. # field is required, but the form is valid because the field is excluded from
  1203. # the form. This is for backwards compatibility.
  1204. form = PriceFormWithoutQuantity({'price': '6.00'})
  1205. self.assertEqual(form.is_valid(), True)
  1206. price = form.save(commit=False)
  1207. with self.assertRaises(ValidationError):
  1208. price.full_clean()
  1209. # The form should not validate fields that it doesn't contain even if they are
  1210. # specified using 'fields', not 'exclude'.
  1211. class Meta:
  1212. model = Price
  1213. fields = ('price',)
  1214. form = PriceFormWithoutQuantity({'price': '6.00'})
  1215. self.assertEqual(form.is_valid(), True)
  1216. # The form should still have an instance of a model that is not complete and
  1217. # not saved into a DB yet.
  1218. self.assertEqual(form.instance.price, Decimal('6.00'))
  1219. self.assertEqual(form.instance.quantity is None, True)
  1220. self.assertEqual(form.instance.pk is None, True)
  1221. # Choices on CharField and IntegerField
  1222. f = ArticleForm()
  1223. with self.assertRaises(ValidationError):
  1224. f.fields['status'].clean('42')
  1225. f = ArticleStatusForm()
  1226. with self.assertRaises(ValidationError):
  1227. f.fields['status'].clean('z')
  1228. def test_foreignkeys_which_use_to_field(self):
  1229. apple = Inventory.objects.create(barcode=86, name='Apple')
  1230. pear = Inventory.objects.create(barcode=22, name='Pear')
  1231. core = Inventory.objects.create(barcode=87, name='Core', parent=apple)
  1232. field = forms.ModelChoiceField(Inventory.objects.all(), to_field_name='barcode')
  1233. self.assertEqual(tuple(field.choices), (
  1234. (u'', u'---------'),
  1235. (86, u'Apple'),
  1236. (87, u'Core'),
  1237. (22, u'Pear')))
  1238. form = InventoryForm(instance=core)
  1239. self.assertHTMLEqual(unicode(form['parent']), '''<select name="parent" id="id_parent">
  1240. <option value="">---------</option>
  1241. <option value="86" selected="selected">Apple</option>
  1242. <option value="87">Core</option>
  1243. <option value="22">Pear</option>
  1244. </select>''')
  1245. data = model_to_dict(core)
  1246. data['parent'] = '22'
  1247. form = InventoryForm(data=data, instance=core)
  1248. core = form.save()
  1249. self.assertEqual(core.parent.name, 'Pear')
  1250. class CategoryForm(forms.ModelForm):
  1251. description = forms.CharField()
  1252. class Meta:
  1253. model = Category
  1254. fields = ['description', 'url']
  1255. self.assertEqual(CategoryForm.base_fields.keys(),
  1256. ['description', 'url'])
  1257. self.assertHTMLEqual(unicode(CategoryForm()), '''<tr><th><label for="id_description">Description:</label></th><td><input type="text" name="description" id="id_description" /></td></tr>
  1258. <tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr>''')
  1259. # to_field_name should also work on ModelMultipleChoiceField ##################
  1260. field = forms.ModelMultipleChoiceField(Inventory.objects.all(), to_field_name='barcode')
  1261. self.assertEqual(tuple(field.choices), ((86, u'Apple'), (87, u'Core'), (22, u'Pear')))
  1262. self.assertEqual(map(lambda o: o.name, field.clean([86])), ['Apple'])
  1263. form = SelectInventoryForm({'items': [87, 22]})
  1264. self.assertEqual(form.is_valid(), True)
  1265. self.assertEqual(len(form.cleaned_data), 1)
  1266. self.assertEqual(map(lambda o: o.name, form.cleaned_data['items']), ['Core', 'Pear'])
  1267. def test_model_field_that_returns_none_to_exclude_itself_with_explicit_fields(self):
  1268. self.assertEqual(CustomFieldForExclusionForm.base_fields.keys(), ['name'])
  1269. self.assertHTMLEqual(unicode(CustomFieldForExclusionForm()),
  1270. '''<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="10" /></td></tr>''')