tests.py 73 KB

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