tests.py 78 KB

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