tests.py 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594
  1. from __future__ import unicode_literals
  2. import datetime
  3. import os
  4. from decimal import Decimal
  5. from unittest import skipUnless
  6. from django import forms
  7. from django.core.exceptions import (
  8. NON_FIELD_ERRORS, FieldError, ImproperlyConfigured,
  9. )
  10. from django.core.files.uploadedfile import SimpleUploadedFile
  11. from django.core.validators import ValidationError
  12. from django.db import connection, models
  13. from django.db.models.query import EmptyQuerySet
  14. from django.forms.models import (
  15. ModelFormMetaclass, construct_instance, fields_for_model, model_to_dict,
  16. modelform_factory,
  17. )
  18. from django.template import Context, Template
  19. from django.test import TestCase, skipUnlessDBFeature
  20. from django.utils import six
  21. from django.utils._os import upath
  22. from .models import (
  23. Article, ArticleStatus, Author, Author1, BetterWriter, BigInt, Book,
  24. Category, Character, Colour, ColourfulItem, CommaSeparatedInteger,
  25. CustomErrorMessage, CustomFF, CustomFieldForExclusionModel, DateTimePost,
  26. DerivedBook, DerivedPost, Document, ExplicitPK, FilePathModel,
  27. FlexibleDatePost, Homepage, ImprovedArticle, ImprovedArticleWithParentLink,
  28. Inventory, Person, Photo, Post, Price, Product, Publication, Student,
  29. StumpJoke, TextFile, Triple, Writer, WriterProfile, test_images,
  30. )
  31. if test_images:
  32. from .models import ImageFile, OptionalImageFile
  33. class ImageFileForm(forms.ModelForm):
  34. class Meta:
  35. model = ImageFile
  36. fields = '__all__'
  37. class OptionalImageFileForm(forms.ModelForm):
  38. class Meta:
  39. model = OptionalImageFile
  40. fields = '__all__'
  41. class ProductForm(forms.ModelForm):
  42. class Meta:
  43. model = Product
  44. fields = '__all__'
  45. class PriceForm(forms.ModelForm):
  46. class Meta:
  47. model = Price
  48. fields = '__all__'
  49. class BookForm(forms.ModelForm):
  50. class Meta:
  51. model = Book
  52. fields = '__all__'
  53. class DerivedBookForm(forms.ModelForm):
  54. class Meta:
  55. model = DerivedBook
  56. fields = '__all__'
  57. class ExplicitPKForm(forms.ModelForm):
  58. class Meta:
  59. model = ExplicitPK
  60. fields = ('key', 'desc',)
  61. class PostForm(forms.ModelForm):
  62. class Meta:
  63. model = Post
  64. fields = '__all__'
  65. class DerivedPostForm(forms.ModelForm):
  66. class Meta:
  67. model = DerivedPost
  68. fields = '__all__'
  69. class CustomWriterForm(forms.ModelForm):
  70. name = forms.CharField(required=False)
  71. class Meta:
  72. model = Writer
  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 RoykoForm(forms.ModelForm):
  83. class Meta:
  84. model = Writer
  85. fields = '__all__'
  86. class ArticleStatusForm(forms.ModelForm):
  87. class Meta:
  88. model = ArticleStatus
  89. fields = '__all__'
  90. class InventoryForm(forms.ModelForm):
  91. class Meta:
  92. model = Inventory
  93. fields = '__all__'
  94. class SelectInventoryForm(forms.Form):
  95. items = forms.ModelMultipleChoiceField(Inventory.objects.all(), to_field_name='barcode')
  96. class CustomFieldForExclusionForm(forms.ModelForm):
  97. class Meta:
  98. model = CustomFieldForExclusionModel
  99. fields = ['name', 'markup']
  100. class TextFileForm(forms.ModelForm):
  101. class Meta:
  102. model = TextFile
  103. fields = '__all__'
  104. class BigIntForm(forms.ModelForm):
  105. class Meta:
  106. model = BigInt
  107. fields = '__all__'
  108. class ModelFormWithMedia(forms.ModelForm):
  109. class Media:
  110. js = ('/some/form/javascript',)
  111. css = {
  112. 'all': ('/some/form/css',)
  113. }
  114. class Meta:
  115. model = TextFile
  116. fields = '__all__'
  117. class CustomErrorMessageForm(forms.ModelForm):
  118. name1 = forms.CharField(error_messages={'invalid': 'Form custom error message.'})
  119. class Meta:
  120. fields = '__all__'
  121. model = CustomErrorMessage
  122. class ModelFormBaseTest(TestCase):
  123. def test_base_form(self):
  124. self.assertEqual(list(BaseCategoryForm.base_fields),
  125. ['name', 'slug', 'url'])
  126. def test_no_model_class(self):
  127. class NoModelModelForm(forms.ModelForm):
  128. pass
  129. self.assertRaises(ValueError, NoModelModelForm)
  130. def test_empty_fields_to_fields_for_model(self):
  131. """
  132. An argument of fields=() to fields_for_model should return an empty dictionary
  133. """
  134. field_dict = fields_for_model(Person, fields=())
  135. self.assertEqual(len(field_dict), 0)
  136. def test_empty_fields_on_modelform(self):
  137. """
  138. No fields on a ModelForm should actually result in no fields.
  139. """
  140. class EmptyPersonForm(forms.ModelForm):
  141. class Meta:
  142. model = Person
  143. fields = ()
  144. form = EmptyPersonForm()
  145. self.assertEqual(len(form.fields), 0)
  146. def test_empty_fields_to_construct_instance(self):
  147. """
  148. No fields should be set on a model instance if construct_instance receives fields=().
  149. """
  150. form = modelform_factory(Person, fields="__all__")({'name': 'John Doe'})
  151. self.assertTrue(form.is_valid())
  152. instance = construct_instance(form, Person(), fields=())
  153. self.assertEqual(instance.name, '')
  154. def test_blank_with_null_foreign_key_field(self):
  155. """
  156. #13776 -- ModelForm's with models having a FK set to null=False and
  157. required=False should be valid.
  158. """
  159. class FormForTestingIsValid(forms.ModelForm):
  160. class Meta:
  161. model = Student
  162. fields = '__all__'
  163. def __init__(self, *args, **kwargs):
  164. super(FormForTestingIsValid, self).__init__(*args, **kwargs)
  165. self.fields['character'].required = False
  166. char = Character.objects.create(username='user',
  167. last_action=datetime.datetime.today())
  168. data = {'study': 'Engineering'}
  169. data2 = {'study': 'Engineering', 'character': char.pk}
  170. # form is valid because required=False for field 'character'
  171. f1 = FormForTestingIsValid(data)
  172. self.assertTrue(f1.is_valid())
  173. f2 = FormForTestingIsValid(data2)
  174. self.assertTrue(f2.is_valid())
  175. obj = f2.save()
  176. self.assertEqual(obj.character, char)
  177. def test_missing_fields_attribute(self):
  178. message = (
  179. "Creating a ModelForm without either the 'fields' attribute "
  180. "or the 'exclude' attribute is prohibited; form "
  181. "MissingFieldsForm needs updating."
  182. )
  183. with self.assertRaisesMessage(ImproperlyConfigured, message):
  184. class MissingFieldsForm(forms.ModelForm):
  185. class Meta:
  186. model = Category
  187. def test_extra_fields(self):
  188. class ExtraFields(BaseCategoryForm):
  189. some_extra_field = forms.BooleanField()
  190. self.assertEqual(list(ExtraFields.base_fields),
  191. ['name', 'slug', 'url', 'some_extra_field'])
  192. def test_extra_field_model_form(self):
  193. try:
  194. class ExtraPersonForm(forms.ModelForm):
  195. """ ModelForm with an extra field """
  196. age = forms.IntegerField()
  197. class Meta:
  198. model = Person
  199. fields = ('name', 'no-field')
  200. except FieldError as e:
  201. # Make sure the exception contains some reference to the
  202. # field responsible for the problem.
  203. self.assertIn('no-field', e.args[0])
  204. else:
  205. self.fail('Invalid "no-field" field not caught')
  206. def test_extra_declared_field_model_form(self):
  207. try:
  208. class ExtraPersonForm(forms.ModelForm):
  209. """ ModelForm with an extra field """
  210. age = forms.IntegerField()
  211. class Meta:
  212. model = Person
  213. fields = ('name', 'age')
  214. except FieldError:
  215. self.fail('Declarative field raised FieldError incorrectly')
  216. def test_extra_field_modelform_factory(self):
  217. self.assertRaises(FieldError, modelform_factory,
  218. Person, fields=['no-field', 'name'])
  219. def test_replace_field(self):
  220. class ReplaceField(forms.ModelForm):
  221. url = forms.BooleanField()
  222. class Meta:
  223. model = Category
  224. fields = '__all__'
  225. self.assertIsInstance(ReplaceField.base_fields['url'],
  226. forms.fields.BooleanField)
  227. def test_replace_field_variant_2(self):
  228. # Should have the same result as before,
  229. # but 'fields' attribute specified differently
  230. class ReplaceField(forms.ModelForm):
  231. url = forms.BooleanField()
  232. class Meta:
  233. model = Category
  234. fields = ['url']
  235. self.assertIsInstance(ReplaceField.base_fields['url'],
  236. forms.fields.BooleanField)
  237. def test_replace_field_variant_3(self):
  238. # Should have the same result as before,
  239. # but 'fields' attribute specified differently
  240. class ReplaceField(forms.ModelForm):
  241. url = forms.BooleanField()
  242. class Meta:
  243. model = Category
  244. fields = [] # url will still appear, since it is explicit above
  245. self.assertIsInstance(ReplaceField.base_fields['url'],
  246. forms.fields.BooleanField)
  247. def test_override_field(self):
  248. class WriterForm(forms.ModelForm):
  249. book = forms.CharField(required=False)
  250. class Meta:
  251. model = Writer
  252. fields = '__all__'
  253. wf = WriterForm({'name': 'Richard Lockridge'})
  254. self.assertTrue(wf.is_valid())
  255. def test_limit_nonexistent_field(self):
  256. expected_msg = 'Unknown field(s) (nonexistent) specified for Category'
  257. with self.assertRaisesMessage(FieldError, expected_msg):
  258. class InvalidCategoryForm(forms.ModelForm):
  259. class Meta:
  260. model = Category
  261. fields = ['nonexistent']
  262. def test_limit_fields_with_string(self):
  263. expected_msg = "CategoryForm.Meta.fields cannot be a string. Did you mean to type: ('url',)?"
  264. with self.assertRaisesMessage(TypeError, expected_msg):
  265. class CategoryForm(forms.ModelForm):
  266. class Meta:
  267. model = Category
  268. fields = ('url') # note the missing comma
  269. def test_exclude_fields(self):
  270. class ExcludeFields(forms.ModelForm):
  271. class Meta:
  272. model = Category
  273. exclude = ['url']
  274. self.assertEqual(list(ExcludeFields.base_fields),
  275. ['name', 'slug'])
  276. def test_exclude_nonexistent_field(self):
  277. class ExcludeFields(forms.ModelForm):
  278. class Meta:
  279. model = Category
  280. exclude = ['nonexistent']
  281. self.assertEqual(list(ExcludeFields.base_fields),
  282. ['name', 'slug', 'url'])
  283. def test_exclude_fields_with_string(self):
  284. expected_msg = "CategoryForm.Meta.exclude cannot be a string. Did you mean to type: ('url',)?"
  285. with self.assertRaisesMessage(TypeError, expected_msg):
  286. class CategoryForm(forms.ModelForm):
  287. class Meta:
  288. model = Category
  289. exclude = ('url') # note the missing comma
  290. def test_exclude_and_validation(self):
  291. # This Price instance generated by this form is not valid because the quantity
  292. # field is required, but the form is valid because the field is excluded from
  293. # the form. This is for backwards compatibility.
  294. class PriceFormWithoutQuantity(forms.ModelForm):
  295. class Meta:
  296. model = Price
  297. exclude = ('quantity',)
  298. form = PriceFormWithoutQuantity({'price': '6.00'})
  299. self.assertTrue(form.is_valid())
  300. price = form.save(commit=False)
  301. with self.assertRaises(ValidationError):
  302. price.full_clean()
  303. # The form should not validate fields that it doesn't contain even if they are
  304. # specified using 'fields', not 'exclude'.
  305. class PriceFormWithoutQuantity(forms.ModelForm):
  306. class Meta:
  307. model = Price
  308. fields = ('price',)
  309. form = PriceFormWithoutQuantity({'price': '6.00'})
  310. self.assertTrue(form.is_valid())
  311. # The form should still have an instance of a model that is not complete and
  312. # not saved into a DB yet.
  313. self.assertEqual(form.instance.price, Decimal('6.00'))
  314. self.assertIsNone(form.instance.quantity)
  315. self.assertIsNone(form.instance.pk)
  316. def test_confused_form(self):
  317. class ConfusedForm(forms.ModelForm):
  318. """ Using 'fields' *and* 'exclude'. Not sure why you'd want to do
  319. this, but uh, "be liberal in what you accept" and all.
  320. """
  321. class Meta:
  322. model = Category
  323. fields = ['name', 'url']
  324. exclude = ['url']
  325. self.assertEqual(list(ConfusedForm.base_fields),
  326. ['name'])
  327. def test_mixmodel_form(self):
  328. class MixModelForm(BaseCategoryForm):
  329. """ Don't allow more than one 'model' definition in the
  330. inheritance hierarchy. Technically, it would generate a valid
  331. form, but the fact that the resulting save method won't deal with
  332. multiple objects is likely to trip up people not familiar with the
  333. mechanics.
  334. """
  335. class Meta:
  336. model = Article
  337. fields = '__all__'
  338. # MixModelForm is now an Article-related thing, because MixModelForm.Meta
  339. # overrides BaseCategoryForm.Meta.
  340. self.assertEqual(
  341. list(MixModelForm.base_fields),
  342. ['headline', 'slug', 'pub_date', 'writer', 'article', 'categories', 'status']
  343. )
  344. def test_article_form(self):
  345. self.assertEqual(
  346. list(ArticleForm.base_fields),
  347. ['headline', 'slug', 'pub_date', 'writer', 'article', 'categories', 'status']
  348. )
  349. def test_bad_form(self):
  350. # First class with a Meta class wins...
  351. class BadForm(ArticleForm, BaseCategoryForm):
  352. pass
  353. self.assertEqual(
  354. list(BadForm.base_fields),
  355. ['headline', 'slug', 'pub_date', 'writer', 'article', 'categories', 'status']
  356. )
  357. def test_invalid_meta_model(self):
  358. class InvalidModelForm(forms.ModelForm):
  359. class Meta:
  360. pass # no model
  361. # Can't create new form
  362. with self.assertRaises(ValueError):
  363. InvalidModelForm()
  364. # Even if you provide a model instance
  365. with self.assertRaises(ValueError):
  366. InvalidModelForm(instance=Category)
  367. def test_subcategory_form(self):
  368. class SubCategoryForm(BaseCategoryForm):
  369. """ Subclassing without specifying a Meta on the class will use
  370. the parent's Meta (or the first parent in the MRO if there are
  371. multiple parent classes).
  372. """
  373. pass
  374. self.assertEqual(list(SubCategoryForm.base_fields),
  375. ['name', 'slug', 'url'])
  376. def test_subclassmeta_form(self):
  377. class SomeCategoryForm(forms.ModelForm):
  378. checkbox = forms.BooleanField()
  379. class Meta:
  380. model = Category
  381. fields = '__all__'
  382. class SubclassMeta(SomeCategoryForm):
  383. """ We can also subclass the Meta inner class to change the fields
  384. list.
  385. """
  386. class Meta(SomeCategoryForm.Meta):
  387. exclude = ['url']
  388. self.assertHTMLEqual(
  389. str(SubclassMeta()),
  390. """<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr>
  391. <tr><th><label for="id_slug">Slug:</label></th><td><input id="id_slug" type="text" name="slug" maxlength="20" /></td></tr>
  392. <tr><th><label for="id_checkbox">Checkbox:</label></th><td><input type="checkbox" name="checkbox" id="id_checkbox" /></td></tr>"""
  393. )
  394. def test_orderfields_form(self):
  395. class OrderFields(forms.ModelForm):
  396. class Meta:
  397. model = Category
  398. fields = ['url', 'name']
  399. self.assertEqual(list(OrderFields.base_fields),
  400. ['url', 'name'])
  401. self.assertHTMLEqual(
  402. str(OrderFields()),
  403. """<tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr>
  404. <tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr>"""
  405. )
  406. def test_orderfields2_form(self):
  407. class OrderFields2(forms.ModelForm):
  408. class Meta:
  409. model = Category
  410. fields = ['slug', 'url', 'name']
  411. exclude = ['url']
  412. self.assertEqual(list(OrderFields2.base_fields),
  413. ['slug', 'name'])
  414. class FieldOverridesByFormMetaForm(forms.ModelForm):
  415. class Meta:
  416. model = Category
  417. fields = ['name', 'url', 'slug']
  418. widgets = {
  419. 'name': forms.Textarea,
  420. 'url': forms.TextInput(attrs={'class': 'url'})
  421. }
  422. labels = {
  423. 'name': 'Title',
  424. }
  425. help_texts = {
  426. 'slug': 'Watch out! Letters, numbers, underscores and hyphens only.',
  427. }
  428. error_messages = {
  429. 'slug': {
  430. 'invalid': (
  431. "Didn't you read the help text? "
  432. "We said letters, numbers, underscores and hyphens only!"
  433. )
  434. }
  435. }
  436. field_classes = {
  437. 'url': forms.URLField,
  438. }
  439. class TestFieldOverridesByFormMeta(TestCase):
  440. def test_widget_overrides(self):
  441. form = FieldOverridesByFormMetaForm()
  442. self.assertHTMLEqual(
  443. str(form['name']),
  444. '<textarea id="id_name" rows="10" cols="40" name="name" maxlength="20"></textarea>',
  445. )
  446. self.assertHTMLEqual(
  447. str(form['url']),
  448. '<input id="id_url" type="text" class="url" name="url" maxlength="40" />',
  449. )
  450. self.assertHTMLEqual(
  451. str(form['slug']),
  452. '<input id="id_slug" type="text" name="slug" maxlength="20" />',
  453. )
  454. def test_label_overrides(self):
  455. form = FieldOverridesByFormMetaForm()
  456. self.assertHTMLEqual(
  457. str(form['name'].label_tag()),
  458. '<label for="id_name">Title:</label>',
  459. )
  460. self.assertHTMLEqual(
  461. str(form['url'].label_tag()),
  462. '<label for="id_url">The URL:</label>',
  463. )
  464. self.assertHTMLEqual(
  465. str(form['slug'].label_tag()),
  466. '<label for="id_slug">Slug:</label>',
  467. )
  468. def test_help_text_overrides(self):
  469. form = FieldOverridesByFormMetaForm()
  470. self.assertEqual(
  471. form['slug'].help_text,
  472. 'Watch out! Letters, numbers, underscores and hyphens only.',
  473. )
  474. def test_error_messages_overrides(self):
  475. form = FieldOverridesByFormMetaForm(data={
  476. 'name': 'Category',
  477. 'url': 'http://www.example.com/category/',
  478. 'slug': '!%#*@',
  479. })
  480. form.full_clean()
  481. error = [
  482. "Didn't you read the help text? "
  483. "We said letters, numbers, underscores and hyphens only!",
  484. ]
  485. self.assertEqual(form.errors, {'slug': error})
  486. def test_field_type_overrides(self):
  487. form = FieldOverridesByFormMetaForm()
  488. self.assertIs(Category._meta.get_field('url').__class__, models.CharField)
  489. self.assertIsInstance(form.fields['url'], forms.URLField)
  490. class IncompleteCategoryFormWithFields(forms.ModelForm):
  491. """
  492. A form that replaces the model's url field with a custom one. This should
  493. prevent the model field's validation from being called.
  494. """
  495. url = forms.CharField(required=False)
  496. class Meta:
  497. fields = ('name', 'slug')
  498. model = Category
  499. class IncompleteCategoryFormWithExclude(forms.ModelForm):
  500. """
  501. A form that replaces the model's url field with a custom one. This should
  502. prevent the model field's validation from being called.
  503. """
  504. url = forms.CharField(required=False)
  505. class Meta:
  506. exclude = ['url']
  507. model = Category
  508. class ValidationTest(TestCase):
  509. def test_validates_with_replaced_field_not_specified(self):
  510. form = IncompleteCategoryFormWithFields(data={'name': 'some name', 'slug': 'some-slug'})
  511. assert form.is_valid()
  512. def test_validates_with_replaced_field_excluded(self):
  513. form = IncompleteCategoryFormWithExclude(data={'name': 'some name', 'slug': 'some-slug'})
  514. assert form.is_valid()
  515. def test_notrequired_overrides_notblank(self):
  516. form = CustomWriterForm({})
  517. assert form.is_valid()
  518. class UniqueTest(TestCase):
  519. """
  520. unique/unique_together validation.
  521. """
  522. def setUp(self):
  523. self.writer = Writer.objects.create(name='Mike Royko')
  524. def test_simple_unique(self):
  525. form = ProductForm({'slug': 'teddy-bear-blue'})
  526. self.assertTrue(form.is_valid())
  527. obj = form.save()
  528. form = ProductForm({'slug': 'teddy-bear-blue'})
  529. self.assertEqual(len(form.errors), 1)
  530. self.assertEqual(form.errors['slug'], ['Product with this Slug already exists.'])
  531. form = ProductForm({'slug': 'teddy-bear-blue'}, instance=obj)
  532. self.assertTrue(form.is_valid())
  533. def test_unique_together(self):
  534. """ModelForm test of unique_together constraint"""
  535. form = PriceForm({'price': '6.00', 'quantity': '1'})
  536. self.assertTrue(form.is_valid())
  537. form.save()
  538. form = PriceForm({'price': '6.00', 'quantity': '1'})
  539. self.assertFalse(form.is_valid())
  540. self.assertEqual(len(form.errors), 1)
  541. self.assertEqual(form.errors['__all__'], ['Price with this Price and Quantity already exists.'])
  542. def test_multiple_field_unique_together(self):
  543. """
  544. When the same field is involved in multiple unique_together
  545. constraints, we need to make sure we don't remove the data for it
  546. before doing all the validation checking (not just failing after
  547. the first one).
  548. """
  549. class TripleForm(forms.ModelForm):
  550. class Meta:
  551. model = Triple
  552. fields = '__all__'
  553. Triple.objects.create(left=1, middle=2, right=3)
  554. form = TripleForm({'left': '1', 'middle': '2', 'right': '3'})
  555. self.assertFalse(form.is_valid())
  556. form = TripleForm({'left': '1', 'middle': '3', 'right': '1'})
  557. self.assertTrue(form.is_valid())
  558. @skipUnlessDBFeature('supports_nullable_unique_constraints')
  559. def test_unique_null(self):
  560. title = 'I May Be Wrong But I Doubt It'
  561. form = BookForm({'title': title, 'author': self.writer.pk})
  562. self.assertTrue(form.is_valid())
  563. form.save()
  564. form = BookForm({'title': title, 'author': self.writer.pk})
  565. self.assertFalse(form.is_valid())
  566. self.assertEqual(len(form.errors), 1)
  567. self.assertEqual(form.errors['__all__'], ['Book with this Title and Author already exists.'])
  568. form = BookForm({'title': title})
  569. self.assertTrue(form.is_valid())
  570. form.save()
  571. form = BookForm({'title': title})
  572. self.assertTrue(form.is_valid())
  573. def test_inherited_unique(self):
  574. title = 'Boss'
  575. Book.objects.create(title=title, author=self.writer, special_id=1)
  576. form = DerivedBookForm({'title': 'Other', 'author': self.writer.pk, 'special_id': '1', 'isbn': '12345'})
  577. self.assertFalse(form.is_valid())
  578. self.assertEqual(len(form.errors), 1)
  579. self.assertEqual(form.errors['special_id'], ['Book with this Special id already exists.'])
  580. def test_inherited_unique_together(self):
  581. title = 'Boss'
  582. form = BookForm({'title': title, 'author': self.writer.pk})
  583. self.assertTrue(form.is_valid())
  584. form.save()
  585. form = DerivedBookForm({'title': title, 'author': self.writer.pk, 'isbn': '12345'})
  586. self.assertFalse(form.is_valid())
  587. self.assertEqual(len(form.errors), 1)
  588. self.assertEqual(form.errors['__all__'], ['Book with this Title and Author already exists.'])
  589. def test_abstract_inherited_unique(self):
  590. title = 'Boss'
  591. isbn = '12345'
  592. DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn)
  593. form = DerivedBookForm({'title': 'Other', 'author': self.writer.pk, 'isbn': isbn})
  594. self.assertFalse(form.is_valid())
  595. self.assertEqual(len(form.errors), 1)
  596. self.assertEqual(form.errors['isbn'], ['Derived book with this Isbn already exists.'])
  597. def test_abstract_inherited_unique_together(self):
  598. title = 'Boss'
  599. isbn = '12345'
  600. DerivedBook.objects.create(title=title, author=self.writer, isbn=isbn)
  601. form = DerivedBookForm({
  602. 'title': 'Other',
  603. 'author': self.writer.pk,
  604. 'isbn': '9876',
  605. 'suffix1': '0',
  606. 'suffix2': '0'
  607. })
  608. self.assertFalse(form.is_valid())
  609. self.assertEqual(len(form.errors), 1)
  610. self.assertEqual(form.errors['__all__'],
  611. ['Derived book with this Suffix1 and Suffix2 already exists.'])
  612. def test_explicitpk_unspecified(self):
  613. """Test for primary_key being in the form and failing validation."""
  614. form = ExplicitPKForm({'key': '', 'desc': ''})
  615. self.assertFalse(form.is_valid())
  616. def test_explicitpk_unique(self):
  617. """Ensure keys and blank character strings are tested for uniqueness."""
  618. form = ExplicitPKForm({'key': 'key1', 'desc': ''})
  619. self.assertTrue(form.is_valid())
  620. form.save()
  621. form = ExplicitPKForm({'key': 'key1', 'desc': ''})
  622. self.assertFalse(form.is_valid())
  623. self.assertEqual(len(form.errors), 3)
  624. self.assertEqual(form.errors['__all__'], ['Explicit pk with this Key and Desc already exists.'])
  625. self.assertEqual(form.errors['desc'], ['Explicit pk with this Desc already exists.'])
  626. self.assertEqual(form.errors['key'], ['Explicit pk with this Key already exists.'])
  627. def test_unique_for_date(self):
  628. p = Post.objects.create(title="Django 1.0 is released",
  629. slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3))
  630. form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'})
  631. self.assertFalse(form.is_valid())
  632. self.assertEqual(len(form.errors), 1)
  633. self.assertEqual(form.errors['title'], ['Title must be unique for Posted date.'])
  634. form = PostForm({'title': "Work on Django 1.1 begins", 'posted': '2008-09-03'})
  635. self.assertTrue(form.is_valid())
  636. form = PostForm({'title': "Django 1.0 is released", 'posted': '2008-09-04'})
  637. self.assertTrue(form.is_valid())
  638. form = PostForm({'slug': "Django 1.0", 'posted': '2008-01-01'})
  639. self.assertFalse(form.is_valid())
  640. self.assertEqual(len(form.errors), 1)
  641. self.assertEqual(form.errors['slug'], ['Slug must be unique for Posted year.'])
  642. form = PostForm({'subtitle': "Finally", 'posted': '2008-09-30'})
  643. self.assertFalse(form.is_valid())
  644. self.assertEqual(form.errors['subtitle'], ['Subtitle must be unique for Posted month.'])
  645. form = PostForm({'subtitle': "Finally", "title": "Django 1.0 is released",
  646. "slug": "Django 1.0", 'posted': '2008-09-03'}, instance=p)
  647. self.assertTrue(form.is_valid())
  648. form = PostForm({'title': "Django 1.0 is released"})
  649. self.assertFalse(form.is_valid())
  650. self.assertEqual(len(form.errors), 1)
  651. self.assertEqual(form.errors['posted'], ['This field is required.'])
  652. def test_unique_for_date_in_exclude(self):
  653. """
  654. If the date for unique_for_* constraints is excluded from the
  655. ModelForm (in this case 'posted' has editable=False, then the
  656. constraint should be ignored.
  657. """
  658. class DateTimePostForm(forms.ModelForm):
  659. class Meta:
  660. model = DateTimePost
  661. fields = '__all__'
  662. DateTimePost.objects.create(title="Django 1.0 is released",
  663. slug="Django 1.0", subtitle="Finally",
  664. posted=datetime.datetime(2008, 9, 3, 10, 10, 1))
  665. # 'title' has unique_for_date='posted'
  666. form = DateTimePostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'})
  667. self.assertTrue(form.is_valid())
  668. # 'slug' has unique_for_year='posted'
  669. form = DateTimePostForm({'slug': "Django 1.0", 'posted': '2008-01-01'})
  670. self.assertTrue(form.is_valid())
  671. # 'subtitle' has unique_for_month='posted'
  672. form = DateTimePostForm({'subtitle': "Finally", 'posted': '2008-09-30'})
  673. self.assertTrue(form.is_valid())
  674. def test_inherited_unique_for_date(self):
  675. p = Post.objects.create(title="Django 1.0 is released",
  676. slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3))
  677. form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'})
  678. self.assertFalse(form.is_valid())
  679. self.assertEqual(len(form.errors), 1)
  680. self.assertEqual(form.errors['title'], ['Title must be unique for Posted date.'])
  681. form = DerivedPostForm({'title': "Work on Django 1.1 begins", 'posted': '2008-09-03'})
  682. self.assertTrue(form.is_valid())
  683. form = DerivedPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-04'})
  684. self.assertTrue(form.is_valid())
  685. form = DerivedPostForm({'slug': "Django 1.0", 'posted': '2008-01-01'})
  686. self.assertFalse(form.is_valid())
  687. self.assertEqual(len(form.errors), 1)
  688. self.assertEqual(form.errors['slug'], ['Slug must be unique for Posted year.'])
  689. form = DerivedPostForm({'subtitle': "Finally", 'posted': '2008-09-30'})
  690. self.assertFalse(form.is_valid())
  691. self.assertEqual(form.errors['subtitle'], ['Subtitle must be unique for Posted month.'])
  692. form = DerivedPostForm({'subtitle': "Finally", "title": "Django 1.0 is released",
  693. "slug": "Django 1.0", 'posted': '2008-09-03'}, instance=p)
  694. self.assertTrue(form.is_valid())
  695. def test_unique_for_date_with_nullable_date(self):
  696. class FlexDatePostForm(forms.ModelForm):
  697. class Meta:
  698. model = FlexibleDatePost
  699. fields = '__all__'
  700. p = FlexibleDatePost.objects.create(title="Django 1.0 is released",
  701. slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3))
  702. form = FlexDatePostForm({'title': "Django 1.0 is released"})
  703. self.assertTrue(form.is_valid())
  704. form = FlexDatePostForm({'slug': "Django 1.0"})
  705. self.assertTrue(form.is_valid())
  706. form = FlexDatePostForm({'subtitle': "Finally"})
  707. self.assertTrue(form.is_valid())
  708. form = FlexDatePostForm({'subtitle': "Finally", "title": "Django 1.0 is released",
  709. "slug": "Django 1.0"}, instance=p)
  710. self.assertTrue(form.is_valid())
  711. def test_override_unique_message(self):
  712. class CustomProductForm(ProductForm):
  713. class Meta(ProductForm.Meta):
  714. error_messages = {
  715. 'slug': {
  716. 'unique': "%(model_name)s's %(field_label)s not unique.",
  717. }
  718. }
  719. Product.objects.create(slug='teddy-bear-blue')
  720. form = CustomProductForm({'slug': 'teddy-bear-blue'})
  721. self.assertEqual(len(form.errors), 1)
  722. self.assertEqual(form.errors['slug'], ["Product's Slug not unique."])
  723. def test_override_unique_together_message(self):
  724. class CustomPriceForm(PriceForm):
  725. class Meta(PriceForm.Meta):
  726. error_messages = {
  727. NON_FIELD_ERRORS: {
  728. 'unique_together': "%(model_name)s's %(field_labels)s not unique.",
  729. }
  730. }
  731. Price.objects.create(price=6.00, quantity=1)
  732. form = CustomPriceForm({'price': '6.00', 'quantity': '1'})
  733. self.assertEqual(len(form.errors), 1)
  734. self.assertEqual(form.errors[NON_FIELD_ERRORS], ["Price's Price and Quantity not unique."])
  735. def test_override_unique_for_date_message(self):
  736. class CustomPostForm(PostForm):
  737. class Meta(PostForm.Meta):
  738. error_messages = {
  739. 'title': {
  740. 'unique_for_date': "%(model_name)s's %(field_label)s not unique for %(date_field_label)s date.",
  741. }
  742. }
  743. Post.objects.create(title="Django 1.0 is released",
  744. slug="Django 1.0", subtitle="Finally", posted=datetime.date(2008, 9, 3))
  745. form = CustomPostForm({'title': "Django 1.0 is released", 'posted': '2008-09-03'})
  746. self.assertEqual(len(form.errors), 1)
  747. self.assertEqual(form.errors['title'], ["Post's Title not unique for Posted date."])
  748. class ModelToDictTests(TestCase):
  749. """
  750. Tests for forms.models.model_to_dict
  751. """
  752. def test_model_to_dict_many_to_many(self):
  753. categories = [
  754. Category(name='TestName1', slug='TestName1', url='url1'),
  755. Category(name='TestName2', slug='TestName2', url='url2'),
  756. Category(name='TestName3', slug='TestName3', url='url3')
  757. ]
  758. for c in categories:
  759. c.save()
  760. writer = Writer(name='Test writer')
  761. writer.save()
  762. art = Article(
  763. headline='Test article',
  764. slug='test-article',
  765. pub_date=datetime.date(1988, 1, 4),
  766. writer=writer,
  767. article='Hello.'
  768. )
  769. art.save()
  770. for c in categories:
  771. art.categories.add(c)
  772. art.save()
  773. with self.assertNumQueries(1):
  774. d = model_to_dict(art)
  775. # Ensure all many-to-many categories appear in model_to_dict
  776. for c in categories:
  777. self.assertIn(c.pk, d['categories'])
  778. # Ensure many-to-many relation appears as a list
  779. self.assertIsInstance(d['categories'], list)
  780. def test_reuse_prefetched(self):
  781. # model_to_dict should not hit the database if it can reuse
  782. # the data populated by prefetch_related.
  783. categories = [
  784. Category(name='TestName1', slug='TestName1', url='url1'),
  785. Category(name='TestName2', slug='TestName2', url='url2'),
  786. Category(name='TestName3', slug='TestName3', url='url3')
  787. ]
  788. for c in categories:
  789. c.save()
  790. writer = Writer(name='Test writer')
  791. writer.save()
  792. art = Article(
  793. headline='Test article',
  794. slug='test-article',
  795. pub_date=datetime.date(1988, 1, 4),
  796. writer=writer,
  797. article='Hello.'
  798. )
  799. art.save()
  800. for c in categories:
  801. art.categories.add(c)
  802. art = Article.objects.prefetch_related('categories').get(pk=art.pk)
  803. with self.assertNumQueries(0):
  804. d = model_to_dict(art)
  805. # Ensure all many-to-many categories appear in model_to_dict
  806. for c in categories:
  807. self.assertIn(c.pk, d['categories'])
  808. # Ensure many-to-many relation appears as a list
  809. self.assertIsInstance(d['categories'], list)
  810. class ModelFormBasicTests(TestCase):
  811. def create_basic_data(self):
  812. self.c1 = Category.objects.create(
  813. name="Entertainment", slug="entertainment", url="entertainment")
  814. self.c2 = Category.objects.create(
  815. name="It's a test", slug="its-test", url="test")
  816. self.c3 = Category.objects.create(
  817. name="Third test", slug="third-test", url="third")
  818. self.w_royko = Writer.objects.create(name='Mike Royko')
  819. self.w_woodward = Writer.objects.create(name='Bob Woodward')
  820. def test_base_form(self):
  821. self.assertEqual(Category.objects.count(), 0)
  822. f = BaseCategoryForm()
  823. self.assertHTMLEqual(
  824. str(f),
  825. """<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr>
  826. <tr><th><label for="id_slug">Slug:</label></th><td><input id="id_slug" type="text" name="slug" maxlength="20" /></td></tr>
  827. <tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr>"""
  828. )
  829. self.assertHTMLEqual(
  830. str(f.as_ul()),
  831. """<li><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="20" /></li>
  832. <li><label for="id_slug">Slug:</label> <input id="id_slug" type="text" name="slug" maxlength="20" /></li>
  833. <li><label for="id_url">The URL:</label> <input id="id_url" type="text" name="url" maxlength="40" /></li>"""
  834. )
  835. self.assertHTMLEqual(
  836. str(f["name"]),
  837. """<input id="id_name" type="text" name="name" maxlength="20" />""")
  838. def test_auto_id(self):
  839. f = BaseCategoryForm(auto_id=False)
  840. self.assertHTMLEqual(
  841. str(f.as_ul()),
  842. """<li>Name: <input type="text" name="name" maxlength="20" /></li>
  843. <li>Slug: <input type="text" name="slug" maxlength="20" /></li>
  844. <li>The URL: <input type="text" name="url" maxlength="40" /></li>"""
  845. )
  846. def test_initial_values(self):
  847. self.create_basic_data()
  848. # Initial values can be provided for model forms
  849. f = ArticleForm(
  850. auto_id=False,
  851. initial={
  852. 'headline': 'Your headline here',
  853. 'categories': [str(self.c1.id), str(self.c2.id)]
  854. })
  855. self.assertHTMLEqual(f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="Your headline here" maxlength="50" /></li>
  856. <li>Slug: <input type="text" name="slug" maxlength="50" /></li>
  857. <li>Pub date: <input type="text" name="pub_date" /></li>
  858. <li>Writer: <select name="writer">
  859. <option value="" selected="selected">---------</option>
  860. <option value="%s">Bob Woodward</option>
  861. <option value="%s">Mike Royko</option>
  862. </select></li>
  863. <li>Article: <textarea rows="10" cols="40" name="article"></textarea></li>
  864. <li>Categories: <select multiple="multiple" name="categories">
  865. <option value="%s" selected="selected">Entertainment</option>
  866. <option value="%s" selected="selected">It&#39;s a test</option>
  867. <option value="%s">Third test</option>
  868. </select></li>
  869. <li>Status: <select name="status">
  870. <option value="" selected="selected">---------</option>
  871. <option value="1">Draft</option>
  872. <option value="2">Pending</option>
  873. <option value="3">Live</option>
  874. </select></li>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk))
  875. # When the ModelForm is passed an instance, that instance's current values are
  876. # inserted as 'initial' data in each Field.
  877. f = RoykoForm(auto_id=False, instance=self.w_royko)
  878. 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>''')
  879. art = Article.objects.create(
  880. headline='Test article',
  881. slug='test-article',
  882. pub_date=datetime.date(1988, 1, 4),
  883. writer=self.w_royko,
  884. article='Hello.'
  885. )
  886. art_id_1 = art.id
  887. f = ArticleForm(auto_id=False, instance=art)
  888. self.assertHTMLEqual(f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="Test article" maxlength="50" /></li>
  889. <li>Slug: <input type="text" name="slug" value="test-article" maxlength="50" /></li>
  890. <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" /></li>
  891. <li>Writer: <select name="writer">
  892. <option value="">---------</option>
  893. <option value="%s">Bob Woodward</option>
  894. <option value="%s" selected="selected">Mike Royko</option>
  895. </select></li>
  896. <li>Article: <textarea rows="10" cols="40" name="article">Hello.</textarea></li>
  897. <li>Categories: <select multiple="multiple" name="categories">
  898. <option value="%s">Entertainment</option>
  899. <option value="%s">It&#39;s a test</option>
  900. <option value="%s">Third test</option>
  901. </select></li>
  902. <li>Status: <select name="status">
  903. <option value="" selected="selected">---------</option>
  904. <option value="1">Draft</option>
  905. <option value="2">Pending</option>
  906. <option value="3">Live</option>
  907. </select></li>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk))
  908. f = ArticleForm({
  909. 'headline': 'Test headline',
  910. 'slug': 'test-headline',
  911. 'pub_date': '1984-02-06',
  912. 'writer': six.text_type(self.w_royko.pk),
  913. 'article': 'Hello.'
  914. }, instance=art)
  915. self.assertEqual(f.errors, {})
  916. self.assertTrue(f.is_valid())
  917. test_art = f.save()
  918. self.assertEqual(test_art.id, art_id_1)
  919. test_art = Article.objects.get(id=art_id_1)
  920. self.assertEqual(test_art.headline, 'Test headline')
  921. def test_m2m_initial_callable(self):
  922. """
  923. Regression for #10349: A callable can be provided as the initial value for an m2m field
  924. """
  925. self.maxDiff = 1200
  926. self.create_basic_data()
  927. # Set up a callable initial value
  928. def formfield_for_dbfield(db_field, **kwargs):
  929. if db_field.name == 'categories':
  930. kwargs['initial'] = lambda: Category.objects.all().order_by('name')[:2]
  931. return db_field.formfield(**kwargs)
  932. # Create a ModelForm, instantiate it, and check that the output is as expected
  933. ModelForm = modelform_factory(Article, fields=['headline', 'categories'],
  934. formfield_callback=formfield_for_dbfield)
  935. form = ModelForm()
  936. self.assertHTMLEqual(form.as_ul(), """<li><label for="id_headline">Headline:</label> <input id="id_headline" type="text" name="headline" maxlength="50" /></li>
  937. <li><label for="id_categories">Categories:</label> <select multiple="multiple" name="categories" id="id_categories">
  938. <option value="%d" selected="selected">Entertainment</option>
  939. <option value="%d" selected="selected">It&39;s a test</option>
  940. <option value="%d">Third test</option>
  941. </select></li>"""
  942. % (self.c1.pk, self.c2.pk, self.c3.pk))
  943. def test_basic_creation(self):
  944. self.assertEqual(Category.objects.count(), 0)
  945. f = BaseCategoryForm({'name': 'Entertainment',
  946. 'slug': 'entertainment',
  947. 'url': 'entertainment'})
  948. self.assertTrue(f.is_valid())
  949. self.assertEqual(f.cleaned_data['name'], 'Entertainment')
  950. self.assertEqual(f.cleaned_data['slug'], 'entertainment')
  951. self.assertEqual(f.cleaned_data['url'], 'entertainment')
  952. c1 = f.save()
  953. # Testing whether the same object is returned from the
  954. # ORM... not the fastest way...
  955. self.assertEqual(Category.objects.count(), 1)
  956. self.assertEqual(c1, Category.objects.all()[0])
  957. self.assertEqual(c1.name, "Entertainment")
  958. def test_save_commit_false(self):
  959. # If you call save() with commit=False, then it will return an object that
  960. # hasn't yet been saved to the database. In this case, it's up to you to call
  961. # save() on the resulting model instance.
  962. f = BaseCategoryForm({'name': 'Third test', 'slug': 'third-test', 'url': 'third'})
  963. self.assertTrue(f.is_valid())
  964. c1 = f.save(commit=False)
  965. self.assertEqual(c1.name, "Third test")
  966. self.assertEqual(Category.objects.count(), 0)
  967. c1.save()
  968. self.assertEqual(Category.objects.count(), 1)
  969. def test_save_with_data_errors(self):
  970. # If you call save() with invalid data, you'll get a ValueError.
  971. f = BaseCategoryForm({'name': '', 'slug': 'not a slug!', 'url': 'foo'})
  972. self.assertEqual(f.errors['name'], ['This field is required.'])
  973. self.assertEqual(f.errors['slug'], ["Enter a valid 'slug' consisting of letters, numbers, underscores or hyphens."])
  974. self.assertEqual(f.cleaned_data, {'url': 'foo'})
  975. with self.assertRaises(ValueError):
  976. f.save()
  977. f = BaseCategoryForm({'name': '', 'slug': '', 'url': 'foo'})
  978. with self.assertRaises(ValueError):
  979. f.save()
  980. def test_multi_fields(self):
  981. self.create_basic_data()
  982. self.maxDiff = None
  983. # ManyToManyFields are represented by a MultipleChoiceField, ForeignKeys and any
  984. # fields with the 'choices' attribute are represented by a ChoiceField.
  985. f = ArticleForm(auto_id=False)
  986. self.assertHTMLEqual(six.text_type(f), '''<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" /></td></tr>
  987. <tr><th>Slug:</th><td><input type="text" name="slug" maxlength="50" /></td></tr>
  988. <tr><th>Pub date:</th><td><input type="text" name="pub_date" /></td></tr>
  989. <tr><th>Writer:</th><td><select name="writer">
  990. <option value="" selected="selected">---------</option>
  991. <option value="%s">Bob Woodward</option>
  992. <option value="%s">Mike Royko</option>
  993. </select></td></tr>
  994. <tr><th>Article:</th><td><textarea rows="10" cols="40" name="article"></textarea></td></tr>
  995. <tr><th>Categories:</th><td><select multiple="multiple" name="categories">
  996. <option value="%s">Entertainment</option>
  997. <option value="%s">It&#39;s a test</option>
  998. <option value="%s">Third test</option>
  999. </select></td></tr>
  1000. <tr><th>Status:</th><td><select name="status">
  1001. <option value="" selected="selected">---------</option>
  1002. <option value="1">Draft</option>
  1003. <option value="2">Pending</option>
  1004. <option value="3">Live</option>
  1005. </select></td></tr>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk))
  1006. # Add some categories and test the many-to-many form output.
  1007. new_art = Article.objects.create(
  1008. article="Hello.", headline="New headline", slug="new-headline",
  1009. pub_date=datetime.date(1988, 1, 4), writer=self.w_royko)
  1010. new_art.categories.add(Category.objects.get(name='Entertainment'))
  1011. self.assertQuerysetEqual(new_art.categories.all(), ["Entertainment"])
  1012. f = ArticleForm(auto_id=False, instance=new_art)
  1013. self.assertHTMLEqual(f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" /></li>
  1014. <li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" /></li>
  1015. <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" /></li>
  1016. <li>Writer: <select name="writer">
  1017. <option value="">---------</option>
  1018. <option value="%s">Bob Woodward</option>
  1019. <option value="%s" selected="selected">Mike Royko</option>
  1020. </select></li>
  1021. <li>Article: <textarea rows="10" cols="40" name="article">Hello.</textarea></li>
  1022. <li>Categories: <select multiple="multiple" name="categories">
  1023. <option value="%s" selected="selected">Entertainment</option>
  1024. <option value="%s">It&#39;s a test</option>
  1025. <option value="%s">Third test</option>
  1026. </select></li>
  1027. <li>Status: <select name="status">
  1028. <option value="" selected="selected">---------</option>
  1029. <option value="1">Draft</option>
  1030. <option value="2">Pending</option>
  1031. <option value="3">Live</option>
  1032. </select></li>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk))
  1033. def test_subset_fields(self):
  1034. # You can restrict a form to a subset of the complete list of fields
  1035. # by providing a 'fields' argument. If you try to save a
  1036. # model created with such a form, you need to ensure that the fields
  1037. # that are _not_ on the form have default values, or are allowed to have
  1038. # a value of None. If a field isn't specified on a form, the object created
  1039. # from the form can't provide a value for that field!
  1040. class PartialArticleForm(forms.ModelForm):
  1041. class Meta:
  1042. model = Article
  1043. fields = ('headline', 'pub_date')
  1044. f = PartialArticleForm(auto_id=False)
  1045. self.assertHTMLEqual(six.text_type(f), '''<tr><th>Headline:</th><td><input type="text" name="headline" maxlength="50" /></td></tr>
  1046. <tr><th>Pub date:</th><td><input type="text" name="pub_date" /></td></tr>''')
  1047. # You can create a form over a subset of the available fields
  1048. # by specifying a 'fields' argument to form_for_instance.
  1049. class PartialArticleFormWithSlug(forms.ModelForm):
  1050. class Meta:
  1051. model = Article
  1052. fields = ('headline', 'slug', 'pub_date')
  1053. w_royko = Writer.objects.create(name='Mike Royko')
  1054. art = Article.objects.create(
  1055. article="Hello.", headline="New headline", slug="new-headline",
  1056. pub_date=datetime.date(1988, 1, 4), writer=w_royko)
  1057. f = PartialArticleFormWithSlug({
  1058. 'headline': 'New headline',
  1059. 'slug': 'new-headline',
  1060. 'pub_date': '1988-01-04'
  1061. }, auto_id=False, instance=art)
  1062. self.assertHTMLEqual(f.as_ul(), '''<li>Headline: <input type="text" name="headline" value="New headline" maxlength="50" /></li>
  1063. <li>Slug: <input type="text" name="slug" value="new-headline" maxlength="50" /></li>
  1064. <li>Pub date: <input type="text" name="pub_date" value="1988-01-04" /></li>''')
  1065. self.assertTrue(f.is_valid())
  1066. new_art = f.save()
  1067. self.assertEqual(new_art.id, art.id)
  1068. new_art = Article.objects.get(id=art.id)
  1069. self.assertEqual(new_art.headline, 'New headline')
  1070. def test_m2m_editing(self):
  1071. self.create_basic_data()
  1072. form_data = {
  1073. 'headline': 'New headline',
  1074. 'slug': 'new-headline',
  1075. 'pub_date': '1988-01-04',
  1076. 'writer': six.text_type(self.w_royko.pk),
  1077. 'article': 'Hello.',
  1078. 'categories': [six.text_type(self.c1.id), six.text_type(self.c2.id)]
  1079. }
  1080. # Create a new article, with categories, via the form.
  1081. f = ArticleForm(form_data)
  1082. new_art = f.save()
  1083. new_art = Article.objects.get(id=new_art.id)
  1084. art_id_1 = new_art.id
  1085. self.assertQuerysetEqual(new_art.categories.order_by('name'),
  1086. ["Entertainment", "It's a test"])
  1087. # Now, submit form data with no categories. This deletes the existing categories.
  1088. form_data['categories'] = []
  1089. f = ArticleForm(form_data, instance=new_art)
  1090. new_art = f.save()
  1091. self.assertEqual(new_art.id, art_id_1)
  1092. new_art = Article.objects.get(id=art_id_1)
  1093. self.assertQuerysetEqual(new_art.categories.all(), [])
  1094. # Create a new article, with no categories, via the form.
  1095. f = ArticleForm(form_data)
  1096. new_art = f.save()
  1097. art_id_2 = new_art.id
  1098. self.assertNotIn(art_id_2, (None, art_id_1))
  1099. new_art = Article.objects.get(id=art_id_2)
  1100. self.assertQuerysetEqual(new_art.categories.all(), [])
  1101. # Create a new article, with categories, via the form, but use commit=False.
  1102. # The m2m data won't be saved until save_m2m() is invoked on the form.
  1103. form_data['categories'] = [six.text_type(self.c1.id), six.text_type(self.c2.id)]
  1104. f = ArticleForm(form_data)
  1105. new_art = f.save(commit=False)
  1106. # Manually save the instance
  1107. new_art.save()
  1108. art_id_3 = new_art.id
  1109. self.assertNotIn(art_id_3, (None, art_id_1, art_id_2))
  1110. # The instance doesn't have m2m data yet
  1111. new_art = Article.objects.get(id=art_id_3)
  1112. self.assertQuerysetEqual(new_art.categories.all(), [])
  1113. # Save the m2m data on the form
  1114. f.save_m2m()
  1115. self.assertQuerysetEqual(new_art.categories.order_by('name'),
  1116. ["Entertainment", "It's a test"])
  1117. def test_custom_form_fields(self):
  1118. # Here, we define a custom ModelForm. Because it happens to have the same fields as
  1119. # the Category model, we can just call the form's save() to apply its changes to an
  1120. # existing Category instance.
  1121. class ShortCategory(forms.ModelForm):
  1122. name = forms.CharField(max_length=5)
  1123. slug = forms.CharField(max_length=5)
  1124. url = forms.CharField(max_length=3)
  1125. class Meta:
  1126. model = Category
  1127. fields = '__all__'
  1128. cat = Category.objects.create(name='Third test')
  1129. form = ShortCategory({'name': 'Third', 'slug': 'third', 'url': '3rd'}, instance=cat)
  1130. self.assertEqual(form.save().name, 'Third')
  1131. self.assertEqual(Category.objects.get(id=cat.id).name, 'Third')
  1132. def test_runtime_choicefield_populated(self):
  1133. self.maxDiff = None
  1134. # Here, we demonstrate that choices for a ForeignKey ChoiceField are determined
  1135. # at runtime, based on the data in the database when the form is displayed, not
  1136. # the data in the database when the form is instantiated.
  1137. self.create_basic_data()
  1138. f = ArticleForm(auto_id=False)
  1139. self.assertHTMLEqual(f.as_ul(), '''<li>Headline: <input type="text" name="headline" maxlength="50" /></li>
  1140. <li>Slug: <input type="text" name="slug" maxlength="50" /></li>
  1141. <li>Pub date: <input type="text" name="pub_date" /></li>
  1142. <li>Writer: <select name="writer">
  1143. <option value="" selected="selected">---------</option>
  1144. <option value="%s">Bob Woodward</option>
  1145. <option value="%s">Mike Royko</option>
  1146. </select></li>
  1147. <li>Article: <textarea rows="10" cols="40" name="article"></textarea></li>
  1148. <li>Categories: <select multiple="multiple" name="categories">
  1149. <option value="%s">Entertainment</option>
  1150. <option value="%s">It&#39;s a test</option>
  1151. <option value="%s">Third test</option>
  1152. </select> </li>
  1153. <li>Status: <select name="status">
  1154. <option value="" selected="selected">---------</option>
  1155. <option value="1">Draft</option>
  1156. <option value="2">Pending</option>
  1157. <option value="3">Live</option>
  1158. </select></li>''' % (self.w_woodward.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk))
  1159. c4 = Category.objects.create(name='Fourth', url='4th')
  1160. w_bernstein = Writer.objects.create(name='Carl Bernstein')
  1161. self.assertHTMLEqual(f.as_ul(), '''<li>Headline: <input type="text" name="headline" maxlength="50" /></li>
  1162. <li>Slug: <input type="text" name="slug" maxlength="50" /></li>
  1163. <li>Pub date: <input type="text" name="pub_date" /></li>
  1164. <li>Writer: <select name="writer">
  1165. <option value="" selected="selected">---------</option>
  1166. <option value="%s">Bob Woodward</option>
  1167. <option value="%s">Carl Bernstein</option>
  1168. <option value="%s">Mike Royko</option>
  1169. </select></li>
  1170. <li>Article: <textarea rows="10" cols="40" name="article"></textarea></li>
  1171. <li>Categories: <select multiple="multiple" name="categories">
  1172. <option value="%s">Entertainment</option>
  1173. <option value="%s">It&#39;s a test</option>
  1174. <option value="%s">Third test</option>
  1175. <option value="%s">Fourth</option>
  1176. </select></li>
  1177. <li>Status: <select name="status">
  1178. <option value="" selected="selected">---------</option>
  1179. <option value="1">Draft</option>
  1180. <option value="2">Pending</option>
  1181. <option value="3">Live</option>
  1182. </select></li>''' % (self.w_woodward.pk, w_bernstein.pk, self.w_royko.pk, self.c1.pk, self.c2.pk, self.c3.pk, c4.pk))
  1183. class ModelChoiceFieldTests(TestCase):
  1184. def setUp(self):
  1185. self.c1 = Category.objects.create(
  1186. name="Entertainment", slug="entertainment", url="entertainment")
  1187. self.c2 = Category.objects.create(
  1188. name="It's a test", slug="its-test", url="test")
  1189. self.c3 = Category.objects.create(
  1190. name="Third", slug="third-test", url="third")
  1191. # ModelChoiceField ############################################################
  1192. def test_modelchoicefield(self):
  1193. f = forms.ModelChoiceField(Category.objects.all())
  1194. self.assertEqual(list(f.choices), [
  1195. ('', '---------'),
  1196. (self.c1.pk, 'Entertainment'),
  1197. (self.c2.pk, "It's a test"),
  1198. (self.c3.pk, 'Third')])
  1199. with self.assertRaises(ValidationError):
  1200. f.clean('')
  1201. with self.assertRaises(ValidationError):
  1202. f.clean(None)
  1203. with self.assertRaises(ValidationError):
  1204. f.clean(0)
  1205. # Invalid types that require TypeError to be caught (#22808).
  1206. with self.assertRaises(ValidationError):
  1207. f.clean([['fail']])
  1208. with self.assertRaises(ValidationError):
  1209. f.clean([{'foo': 'bar'}])
  1210. self.assertEqual(f.clean(self.c2.id).name, "It's a test")
  1211. self.assertEqual(f.clean(self.c3.id).name, 'Third')
  1212. # Add a Category object *after* the ModelChoiceField has already been
  1213. # instantiated. This proves clean() checks the database during clean() rather
  1214. # than caching it at time of instantiation.
  1215. c4 = Category.objects.create(name='Fourth', url='4th')
  1216. self.assertEqual(f.clean(c4.id).name, 'Fourth')
  1217. # Delete a Category object *after* the ModelChoiceField has already been
  1218. # instantiated. This proves clean() checks the database during clean() rather
  1219. # than caching it at time of instantiation.
  1220. Category.objects.get(url='4th').delete()
  1221. with self.assertRaises(ValidationError):
  1222. f.clean(c4.id)
  1223. def test_modelchoicefield_choices(self):
  1224. f = forms.ModelChoiceField(Category.objects.filter(pk=self.c1.id), required=False)
  1225. self.assertIsNone(f.clean(''))
  1226. self.assertEqual(f.clean(str(self.c1.id)).name, "Entertainment")
  1227. with self.assertRaises(ValidationError):
  1228. f.clean('100')
  1229. # len can be called on choices
  1230. self.assertEqual(len(f.choices), 2)
  1231. # queryset can be changed after the field is created.
  1232. f.queryset = Category.objects.exclude(name='Third')
  1233. self.assertEqual(list(f.choices), [
  1234. ('', '---------'),
  1235. (self.c1.pk, 'Entertainment'),
  1236. (self.c2.pk, "It's a test")])
  1237. self.assertEqual(f.clean(self.c2.id).name, "It's a test")
  1238. with self.assertRaises(ValidationError):
  1239. f.clean(self.c3.id)
  1240. # check that we can safely iterate choices repeatedly
  1241. gen_one = list(f.choices)
  1242. gen_two = f.choices
  1243. self.assertEqual(gen_one[2], (self.c2.pk, "It's a test"))
  1244. self.assertEqual(list(gen_two), [
  1245. ('', '---------'),
  1246. (self.c1.pk, 'Entertainment'),
  1247. (self.c2.pk, "It's a test")])
  1248. # check that we can override the label_from_instance method to print custom labels (#4620)
  1249. f.queryset = Category.objects.all()
  1250. f.label_from_instance = lambda obj: "category " + str(obj)
  1251. self.assertEqual(list(f.choices), [
  1252. ('', '---------'),
  1253. (self.c1.pk, 'category Entertainment'),
  1254. (self.c2.pk, "category It's a test"),
  1255. (self.c3.pk, 'category Third')])
  1256. def test_modelchoicefield_11183(self):
  1257. """
  1258. Regression test for ticket #11183.
  1259. """
  1260. class ModelChoiceForm(forms.Form):
  1261. category = forms.ModelChoiceField(Category.objects.all())
  1262. form1 = ModelChoiceForm()
  1263. field1 = form1.fields['category']
  1264. # To allow the widget to change the queryset of field1.widget.choices correctly,
  1265. # without affecting other forms, the following must hold:
  1266. self.assertIsNot(field1, ModelChoiceForm.base_fields['category'])
  1267. self.assertIs(field1.widget.choices.field, field1)
  1268. def test_modelchoicefield_22745(self):
  1269. """
  1270. #22745 -- Make sure that ModelChoiceField with RadioSelect widget
  1271. doesn't produce unnecessary db queries when accessing its BoundField's
  1272. attrs.
  1273. """
  1274. class ModelChoiceForm(forms.Form):
  1275. category = forms.ModelChoiceField(Category.objects.all(), widget=forms.RadioSelect)
  1276. form = ModelChoiceForm()
  1277. field = form['category'] # BoundField
  1278. template = Template('{{ field.name }}{{ field }}{{ field.help_text }}')
  1279. with self.assertNumQueries(1):
  1280. template.render(Context({'field': field}))
  1281. class ModelMultipleChoiceFieldTests(TestCase):
  1282. def setUp(self):
  1283. self.c1 = Category.objects.create(
  1284. name="Entertainment", slug="entertainment", url="entertainment")
  1285. self.c2 = Category.objects.create(
  1286. name="It's a test", slug="its-test", url="test")
  1287. self.c3 = Category.objects.create(
  1288. name="Third", slug="third-test", url="third")
  1289. def test_model_multiple_choice_field(self):
  1290. f = forms.ModelMultipleChoiceField(Category.objects.all())
  1291. self.assertEqual(list(f.choices), [
  1292. (self.c1.pk, 'Entertainment'),
  1293. (self.c2.pk, "It's a test"),
  1294. (self.c3.pk, 'Third')])
  1295. with self.assertRaises(ValidationError):
  1296. f.clean(None)
  1297. with self.assertRaises(ValidationError):
  1298. f.clean([])
  1299. self.assertQuerysetEqual(f.clean([self.c1.id]), ["Entertainment"])
  1300. self.assertQuerysetEqual(f.clean([self.c2.id]), ["It's a test"])
  1301. self.assertQuerysetEqual(f.clean([str(self.c1.id)]), ["Entertainment"])
  1302. self.assertQuerysetEqual(f.clean([str(self.c1.id), str(self.c2.id)]),
  1303. ["Entertainment", "It's a test"], ordered=False)
  1304. self.assertQuerysetEqual(f.clean([self.c1.id, str(self.c2.id)]),
  1305. ["Entertainment", "It's a test"], ordered=False)
  1306. self.assertQuerysetEqual(f.clean((self.c1.id, str(self.c2.id))),
  1307. ["Entertainment", "It's a test"], ordered=False)
  1308. with self.assertRaises(ValidationError):
  1309. f.clean(['100'])
  1310. with self.assertRaises(ValidationError):
  1311. f.clean('hello')
  1312. with self.assertRaises(ValidationError):
  1313. f.clean(['fail'])
  1314. # Invalid types that require TypeError to be caught (#22808).
  1315. with self.assertRaises(ValidationError):
  1316. f.clean([['fail']])
  1317. with self.assertRaises(ValidationError):
  1318. f.clean([{'foo': 'bar'}])
  1319. # Add a Category object *after* the ModelMultipleChoiceField has already been
  1320. # instantiated. This proves clean() checks the database during clean() rather
  1321. # than caching it at time of instantiation.
  1322. # Note, we are using an id of 1006 here since tests that run before
  1323. # this may create categories with primary keys up to 6. Use
  1324. # a number that will not conflict.
  1325. c6 = Category.objects.create(id=1006, name='Sixth', url='6th')
  1326. self.assertQuerysetEqual(f.clean([c6.id]), ["Sixth"])
  1327. # Delete a Category object *after* the ModelMultipleChoiceField has already been
  1328. # instantiated. This proves clean() checks the database during clean() rather
  1329. # than caching it at time of instantiation.
  1330. Category.objects.get(url='6th').delete()
  1331. with self.assertRaises(ValidationError):
  1332. f.clean([c6.id])
  1333. def test_model_multiple_choice_required_false(self):
  1334. f = forms.ModelMultipleChoiceField(Category.objects.all(), required=False)
  1335. self.assertIsInstance(f.clean([]), EmptyQuerySet)
  1336. self.assertIsInstance(f.clean(()), EmptyQuerySet)
  1337. with self.assertRaises(ValidationError):
  1338. f.clean(['0'])
  1339. with self.assertRaises(ValidationError):
  1340. f.clean([str(self.c3.id), '0'])
  1341. with self.assertRaises(ValidationError):
  1342. f.clean([str(self.c1.id), '0'])
  1343. # queryset can be changed after the field is created.
  1344. f.queryset = Category.objects.exclude(name='Third')
  1345. self.assertEqual(list(f.choices), [
  1346. (self.c1.pk, 'Entertainment'),
  1347. (self.c2.pk, "It's a test")])
  1348. self.assertQuerysetEqual(f.clean([self.c2.id]), ["It's a test"])
  1349. with self.assertRaises(ValidationError):
  1350. f.clean([self.c3.id])
  1351. with self.assertRaises(ValidationError):
  1352. f.clean([str(self.c2.id), str(self.c3.id)])
  1353. f.queryset = Category.objects.all()
  1354. f.label_from_instance = lambda obj: "multicategory " + str(obj)
  1355. self.assertEqual(list(f.choices), [
  1356. (self.c1.pk, 'multicategory Entertainment'),
  1357. (self.c2.pk, "multicategory It's a test"),
  1358. (self.c3.pk, 'multicategory Third')])
  1359. def test_model_multiple_choice_number_of_queries(self):
  1360. """
  1361. Test that ModelMultipleChoiceField does O(1) queries instead of
  1362. O(n) (#10156).
  1363. """
  1364. persons = [Writer.objects.create(name="Person %s" % i) for i in range(30)]
  1365. f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all())
  1366. self.assertNumQueries(1, f.clean, [p.pk for p in persons[1:11:2]])
  1367. def test_model_multiple_choice_run_validators(self):
  1368. """
  1369. Test that ModelMultipleChoiceField run given validators (#14144).
  1370. """
  1371. for i in range(30):
  1372. Writer.objects.create(name="Person %s" % i)
  1373. self._validator_run = False
  1374. def my_validator(value):
  1375. self._validator_run = True
  1376. f = forms.ModelMultipleChoiceField(queryset=Writer.objects.all(),
  1377. validators=[my_validator])
  1378. f.clean([p.pk for p in Writer.objects.all()[8:9]])
  1379. self.assertTrue(self._validator_run)
  1380. def test_model_multiple_choice_show_hidden_initial(self):
  1381. """
  1382. Test support of show_hidden_initial by ModelMultipleChoiceField.
  1383. """
  1384. class WriterForm(forms.Form):
  1385. persons = forms.ModelMultipleChoiceField(show_hidden_initial=True,
  1386. queryset=Writer.objects.all())
  1387. person1 = Writer.objects.create(name="Person 1")
  1388. person2 = Writer.objects.create(name="Person 2")
  1389. form = WriterForm(initial={'persons': [person1, person2]},
  1390. data={'initial-persons': [str(person1.pk), str(person2.pk)],
  1391. 'persons': [str(person1.pk), str(person2.pk)]})
  1392. self.assertTrue(form.is_valid())
  1393. self.assertFalse(form.has_changed())
  1394. form = WriterForm(initial={'persons': [person1, person2]},
  1395. data={'initial-persons': [str(person1.pk), str(person2.pk)],
  1396. 'persons': [str(person2.pk)]})
  1397. self.assertTrue(form.is_valid())
  1398. self.assertTrue(form.has_changed())
  1399. def test_model_multiple_choice_field_22745(self):
  1400. """
  1401. #22745 -- Make sure that ModelMultipleChoiceField with
  1402. CheckboxSelectMultiple widget doesn't produce unnecessary db queries
  1403. when accessing its BoundField's attrs.
  1404. """
  1405. class ModelMultipleChoiceForm(forms.Form):
  1406. categories = forms.ModelMultipleChoiceField(Category.objects.all(), widget=forms.CheckboxSelectMultiple)
  1407. form = ModelMultipleChoiceForm()
  1408. field = form['categories'] # BoundField
  1409. template = Template('{{ field.name }}{{ field }}{{ field.help_text }}')
  1410. with self.assertNumQueries(1):
  1411. template.render(Context({'field': field}))
  1412. def test_show_hidden_initial_changed_queries_efficiently(self):
  1413. class WriterForm(forms.Form):
  1414. persons = forms.ModelMultipleChoiceField(
  1415. show_hidden_initial=True, queryset=Writer.objects.all())
  1416. writers = (Writer.objects.create(name=str(x)) for x in range(0, 50))
  1417. writer_pks = tuple(x.pk for x in writers)
  1418. form = WriterForm(data={'initial-persons': writer_pks})
  1419. with self.assertNumQueries(1):
  1420. self.assertTrue(form.has_changed())
  1421. def test_clean_does_deduplicate_values(self):
  1422. class WriterForm(forms.Form):
  1423. persons = forms.ModelMultipleChoiceField(queryset=Writer.objects.all())
  1424. person1 = Writer.objects.create(name="Person 1")
  1425. form = WriterForm(data={})
  1426. queryset = form.fields['persons'].clean([str(person1.pk)] * 50)
  1427. sql, params = queryset.query.sql_with_params()
  1428. self.assertEqual(len(params), 1)
  1429. class ModelOneToOneFieldTests(TestCase):
  1430. def test_modelform_onetoonefield(self):
  1431. class ImprovedArticleForm(forms.ModelForm):
  1432. class Meta:
  1433. model = ImprovedArticle
  1434. fields = '__all__'
  1435. class ImprovedArticleWithParentLinkForm(forms.ModelForm):
  1436. class Meta:
  1437. model = ImprovedArticleWithParentLink
  1438. fields = '__all__'
  1439. self.assertEqual(list(ImprovedArticleForm.base_fields), ['article'])
  1440. self.assertEqual(list(ImprovedArticleWithParentLinkForm.base_fields), [])
  1441. def test_modelform_subclassed_model(self):
  1442. class BetterWriterForm(forms.ModelForm):
  1443. class Meta:
  1444. # BetterWriter model is a subclass of Writer with an additional `score` field
  1445. model = BetterWriter
  1446. fields = '__all__'
  1447. bw = BetterWriter.objects.create(name='Joe Better', score=10)
  1448. self.assertEqual(sorted(model_to_dict(bw)),
  1449. ['id', 'name', 'score', 'writer_ptr'])
  1450. form = BetterWriterForm({'name': 'Some Name', 'score': 12})
  1451. self.assertTrue(form.is_valid())
  1452. bw2 = form.save()
  1453. self.assertEqual(bw2.score, 12)
  1454. def test_onetoonefield(self):
  1455. class WriterProfileForm(forms.ModelForm):
  1456. class Meta:
  1457. # WriterProfile has a OneToOneField to Writer
  1458. model = WriterProfile
  1459. fields = '__all__'
  1460. self.w_royko = Writer.objects.create(name='Mike Royko')
  1461. self.w_woodward = Writer.objects.create(name='Bob Woodward')
  1462. form = WriterProfileForm()
  1463. self.assertHTMLEqual(form.as_p(), '''<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer">
  1464. <option value="" selected="selected">---------</option>
  1465. <option value="%s">Bob Woodward</option>
  1466. <option value="%s">Mike Royko</option>
  1467. </select></p>
  1468. <p><label for="id_age">Age:</label> <input type="number" name="age" id="id_age" min="0" /></p>''' % (self.w_woodward.pk, self.w_royko.pk))
  1469. data = {
  1470. 'writer': six.text_type(self.w_woodward.pk),
  1471. 'age': '65',
  1472. }
  1473. form = WriterProfileForm(data)
  1474. instance = form.save()
  1475. self.assertEqual(six.text_type(instance), 'Bob Woodward is 65')
  1476. form = WriterProfileForm(instance=instance)
  1477. self.assertHTMLEqual(form.as_p(), '''<p><label for="id_writer">Writer:</label> <select name="writer" id="id_writer">
  1478. <option value="">---------</option>
  1479. <option value="%s" selected="selected">Bob Woodward</option>
  1480. <option value="%s">Mike Royko</option>
  1481. </select></p>
  1482. <p><label for="id_age">Age:</label> <input type="number" name="age" value="65" id="id_age" min="0" /></p>''' % (self.w_woodward.pk, self.w_royko.pk))
  1483. def test_assignment_of_none(self):
  1484. class AuthorForm(forms.ModelForm):
  1485. class Meta:
  1486. model = Author
  1487. fields = ['publication', 'full_name']
  1488. publication = Publication.objects.create(title="Pravda",
  1489. date_published=datetime.date(1991, 8, 22))
  1490. author = Author.objects.create(publication=publication, full_name='John Doe')
  1491. form = AuthorForm({'publication': '', 'full_name': 'John Doe'}, instance=author)
  1492. self.assertTrue(form.is_valid())
  1493. self.assertEqual(form.cleaned_data['publication'], None)
  1494. author = form.save()
  1495. # author object returned from form still retains original publication object
  1496. # that's why we need to retrieve it from database again
  1497. new_author = Author.objects.get(pk=author.pk)
  1498. self.assertEqual(new_author.publication, None)
  1499. def test_assignment_of_none_null_false(self):
  1500. class AuthorForm(forms.ModelForm):
  1501. class Meta:
  1502. model = Author1
  1503. fields = ['publication', 'full_name']
  1504. publication = Publication.objects.create(title="Pravda",
  1505. date_published=datetime.date(1991, 8, 22))
  1506. author = Author1.objects.create(publication=publication, full_name='John Doe')
  1507. form = AuthorForm({'publication': '', 'full_name': 'John Doe'}, instance=author)
  1508. self.assertFalse(form.is_valid())
  1509. class FileAndImageFieldTests(TestCase):
  1510. def test_clean_false(self):
  1511. """
  1512. If the ``clean`` method on a non-required FileField receives False as
  1513. the data (meaning clear the field value), it returns False, regardless
  1514. of the value of ``initial``.
  1515. """
  1516. f = forms.FileField(required=False)
  1517. self.assertEqual(f.clean(False), False)
  1518. self.assertEqual(f.clean(False, 'initial'), False)
  1519. def test_clean_false_required(self):
  1520. """
  1521. If the ``clean`` method on a required FileField receives False as the
  1522. data, it has the same effect as None: initial is returned if non-empty,
  1523. otherwise the validation catches the lack of a required value.
  1524. """
  1525. f = forms.FileField(required=True)
  1526. self.assertEqual(f.clean(False, 'initial'), 'initial')
  1527. self.assertRaises(ValidationError, f.clean, False)
  1528. def test_full_clear(self):
  1529. """
  1530. Integration happy-path test that a model FileField can actually be set
  1531. and cleared via a ModelForm.
  1532. """
  1533. class DocumentForm(forms.ModelForm):
  1534. class Meta:
  1535. model = Document
  1536. fields = '__all__'
  1537. form = DocumentForm()
  1538. self.assertIn('name="myfile"', six.text_type(form))
  1539. self.assertNotIn('myfile-clear', six.text_type(form))
  1540. form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', b'content')})
  1541. self.assertTrue(form.is_valid())
  1542. doc = form.save(commit=False)
  1543. self.assertEqual(doc.myfile.name, 'something.txt')
  1544. form = DocumentForm(instance=doc)
  1545. self.assertIn('myfile-clear', six.text_type(form))
  1546. form = DocumentForm(instance=doc, data={'myfile-clear': 'true'})
  1547. doc = form.save(commit=False)
  1548. self.assertEqual(bool(doc.myfile), False)
  1549. def test_clear_and_file_contradiction(self):
  1550. """
  1551. If the user submits a new file upload AND checks the clear checkbox,
  1552. they get a validation error, and the bound redisplay of the form still
  1553. includes the current file and the clear checkbox.
  1554. """
  1555. class DocumentForm(forms.ModelForm):
  1556. class Meta:
  1557. model = Document
  1558. fields = '__all__'
  1559. form = DocumentForm(files={'myfile': SimpleUploadedFile('something.txt', b'content')})
  1560. self.assertTrue(form.is_valid())
  1561. doc = form.save(commit=False)
  1562. form = DocumentForm(instance=doc,
  1563. files={'myfile': SimpleUploadedFile('something.txt', b'content')},
  1564. data={'myfile-clear': 'true'})
  1565. self.assertTrue(not form.is_valid())
  1566. self.assertEqual(form.errors['myfile'],
  1567. ['Please either submit a file or check the clear checkbox, not both.'])
  1568. rendered = six.text_type(form)
  1569. self.assertIn('something.txt', rendered)
  1570. self.assertIn('myfile-clear', rendered)
  1571. def test_file_field_data(self):
  1572. # Test conditions when files is either not given or empty.
  1573. f = TextFileForm(data={'description': 'Assistance'})
  1574. self.assertFalse(f.is_valid())
  1575. f = TextFileForm(data={'description': 'Assistance'}, files={})
  1576. self.assertFalse(f.is_valid())
  1577. # Upload a file and ensure it all works as expected.
  1578. f = TextFileForm(
  1579. data={'description': 'Assistance'},
  1580. files={'file': SimpleUploadedFile('test1.txt', b'hello world')})
  1581. self.assertTrue(f.is_valid())
  1582. self.assertEqual(type(f.cleaned_data['file']), SimpleUploadedFile)
  1583. instance = f.save()
  1584. self.assertEqual(instance.file.name, 'tests/test1.txt')
  1585. instance.file.delete()
  1586. # If the previous file has been deleted, the file name can be reused
  1587. f = TextFileForm(
  1588. data={'description': 'Assistance'},
  1589. files={'file': SimpleUploadedFile('test1.txt', b'hello world')})
  1590. self.assertTrue(f.is_valid())
  1591. self.assertEqual(type(f.cleaned_data['file']), SimpleUploadedFile)
  1592. instance = f.save()
  1593. self.assertEqual(instance.file.name, 'tests/test1.txt')
  1594. # Check if the max_length attribute has been inherited from the model.
  1595. f = TextFileForm(
  1596. data={'description': 'Assistance'},
  1597. files={'file': SimpleUploadedFile('test-maxlength.txt', b'hello world')})
  1598. self.assertFalse(f.is_valid())
  1599. # Edit an instance that already has the file defined in the model. This will not
  1600. # save the file again, but leave it exactly as it is.
  1601. f = TextFileForm(
  1602. data={'description': 'Assistance'},
  1603. instance=instance)
  1604. self.assertTrue(f.is_valid())
  1605. self.assertEqual(f.cleaned_data['file'].name, 'tests/test1.txt')
  1606. instance = f.save()
  1607. self.assertEqual(instance.file.name, 'tests/test1.txt')
  1608. # Delete the current file since this is not done by Django.
  1609. instance.file.delete()
  1610. # Override the file by uploading a new one.
  1611. f = TextFileForm(
  1612. data={'description': 'Assistance'},
  1613. files={'file': SimpleUploadedFile('test2.txt', b'hello world')}, instance=instance)
  1614. self.assertTrue(f.is_valid())
  1615. instance = f.save()
  1616. self.assertEqual(instance.file.name, 'tests/test2.txt')
  1617. # Delete the current file since this is not done by Django.
  1618. instance.file.delete()
  1619. instance.delete()
  1620. def test_filefield_required_false(self):
  1621. # Test the non-required FileField
  1622. f = TextFileForm(data={'description': 'Assistance'})
  1623. f.fields['file'].required = False
  1624. self.assertTrue(f.is_valid())
  1625. instance = f.save()
  1626. self.assertEqual(instance.file.name, '')
  1627. f = TextFileForm(
  1628. data={'description': 'Assistance'},
  1629. files={'file': SimpleUploadedFile('test3.txt', b'hello world')}, instance=instance)
  1630. self.assertTrue(f.is_valid())
  1631. instance = f.save()
  1632. self.assertEqual(instance.file.name, 'tests/test3.txt')
  1633. # Instance can be edited w/out re-uploading the file and existing file should be preserved.
  1634. f = TextFileForm(
  1635. data={'description': 'New Description'},
  1636. instance=instance)
  1637. f.fields['file'].required = False
  1638. self.assertTrue(f.is_valid())
  1639. instance = f.save()
  1640. self.assertEqual(instance.description, 'New Description')
  1641. self.assertEqual(instance.file.name, 'tests/test3.txt')
  1642. # Delete the current file since this is not done by Django.
  1643. instance.file.delete()
  1644. instance.delete()
  1645. def test_custom_file_field_save(self):
  1646. """
  1647. Regression for #11149: save_form_data should be called only once
  1648. """
  1649. class CFFForm(forms.ModelForm):
  1650. class Meta:
  1651. model = CustomFF
  1652. fields = '__all__'
  1653. # It's enough that the form saves without error -- the custom save routine will
  1654. # generate an AssertionError if it is called more than once during save.
  1655. form = CFFForm(data={'f': None})
  1656. form.save()
  1657. def test_file_field_multiple_save(self):
  1658. """
  1659. Simulate a file upload and check how many times Model.save() gets
  1660. called. Test for bug #639.
  1661. """
  1662. class PhotoForm(forms.ModelForm):
  1663. class Meta:
  1664. model = Photo
  1665. fields = '__all__'
  1666. # Grab an image for testing.
  1667. filename = os.path.join(os.path.dirname(upath(__file__)), "test.png")
  1668. with open(filename, "rb") as fp:
  1669. img = fp.read()
  1670. # Fake a POST QueryDict and FILES MultiValueDict.
  1671. data = {'title': 'Testing'}
  1672. files = {"image": SimpleUploadedFile('test.png', img, 'image/png')}
  1673. form = PhotoForm(data=data, files=files)
  1674. p = form.save()
  1675. try:
  1676. # Check the savecount stored on the object (see the model).
  1677. self.assertEqual(p._savecount, 1)
  1678. finally:
  1679. # Delete the "uploaded" file to avoid clogging /tmp.
  1680. p = Photo.objects.get()
  1681. p.image.delete(save=False)
  1682. def test_file_path_field_blank(self):
  1683. """
  1684. Regression test for #8842: FilePathField(blank=True)
  1685. """
  1686. class FPForm(forms.ModelForm):
  1687. class Meta:
  1688. model = FilePathModel
  1689. fields = '__all__'
  1690. form = FPForm()
  1691. names = [p[1] for p in form['path'].field.choices]
  1692. names.sort()
  1693. self.assertEqual(names, ['---------', '__init__.py', 'models.py', 'tests.py'])
  1694. @skipUnless(test_images, "Pillow not installed")
  1695. def test_image_field(self):
  1696. # ImageField and FileField are nearly identical, but they differ slightly when
  1697. # it comes to validation. This specifically tests that #6302 is fixed for
  1698. # both file fields and image fields.
  1699. with open(os.path.join(os.path.dirname(upath(__file__)), "test.png"), 'rb') as fp:
  1700. image_data = fp.read()
  1701. with open(os.path.join(os.path.dirname(upath(__file__)), "test2.png"), 'rb') as fp:
  1702. image_data2 = fp.read()
  1703. f = ImageFileForm(
  1704. data={'description': 'An image'},
  1705. files={'image': SimpleUploadedFile('test.png', image_data)})
  1706. self.assertTrue(f.is_valid())
  1707. self.assertEqual(type(f.cleaned_data['image']), SimpleUploadedFile)
  1708. instance = f.save()
  1709. self.assertEqual(instance.image.name, 'tests/test.png')
  1710. self.assertEqual(instance.width, 16)
  1711. self.assertEqual(instance.height, 16)
  1712. # Delete the current file since this is not done by Django, but don't save
  1713. # because the dimension fields are not null=True.
  1714. instance.image.delete(save=False)
  1715. f = ImageFileForm(
  1716. data={'description': 'An image'},
  1717. files={'image': SimpleUploadedFile('test.png', image_data)})
  1718. self.assertTrue(f.is_valid())
  1719. self.assertEqual(type(f.cleaned_data['image']), SimpleUploadedFile)
  1720. instance = f.save()
  1721. self.assertEqual(instance.image.name, 'tests/test.png')
  1722. self.assertEqual(instance.width, 16)
  1723. self.assertEqual(instance.height, 16)
  1724. # Edit an instance that already has the (required) image defined in the model. This will not
  1725. # save the image again, but leave it exactly as it is.
  1726. f = ImageFileForm(data={'description': 'Look, it changed'}, instance=instance)
  1727. self.assertTrue(f.is_valid())
  1728. self.assertEqual(f.cleaned_data['image'].name, 'tests/test.png')
  1729. instance = f.save()
  1730. self.assertEqual(instance.image.name, 'tests/test.png')
  1731. self.assertEqual(instance.height, 16)
  1732. self.assertEqual(instance.width, 16)
  1733. # Delete the current file since this is not done by Django, but don't save
  1734. # because the dimension fields are not null=True.
  1735. instance.image.delete(save=False)
  1736. # Override the file by uploading a new one.
  1737. f = ImageFileForm(
  1738. data={'description': 'Changed it'},
  1739. files={'image': SimpleUploadedFile('test2.png', image_data2)}, instance=instance)
  1740. self.assertTrue(f.is_valid())
  1741. instance = f.save()
  1742. self.assertEqual(instance.image.name, 'tests/test2.png')
  1743. self.assertEqual(instance.height, 32)
  1744. self.assertEqual(instance.width, 48)
  1745. # Delete the current file since this is not done by Django, but don't save
  1746. # because the dimension fields are not null=True.
  1747. instance.image.delete(save=False)
  1748. instance.delete()
  1749. f = ImageFileForm(
  1750. data={'description': 'Changed it'},
  1751. files={'image': SimpleUploadedFile('test2.png', image_data2)})
  1752. self.assertTrue(f.is_valid())
  1753. instance = f.save()
  1754. self.assertEqual(instance.image.name, 'tests/test2.png')
  1755. self.assertEqual(instance.height, 32)
  1756. self.assertEqual(instance.width, 48)
  1757. # Delete the current file since this is not done by Django, but don't save
  1758. # because the dimension fields are not null=True.
  1759. instance.image.delete(save=False)
  1760. instance.delete()
  1761. # Test the non-required ImageField
  1762. # Note: In Oracle, we expect a null ImageField to return '' instead of
  1763. # None.
  1764. if connection.features.interprets_empty_strings_as_nulls:
  1765. expected_null_imagefield_repr = ''
  1766. else:
  1767. expected_null_imagefield_repr = None
  1768. f = OptionalImageFileForm(data={'description': 'Test'})
  1769. self.assertTrue(f.is_valid())
  1770. instance = f.save()
  1771. self.assertEqual(instance.image.name, expected_null_imagefield_repr)
  1772. self.assertEqual(instance.width, None)
  1773. self.assertEqual(instance.height, None)
  1774. f = OptionalImageFileForm(
  1775. data={'description': 'And a final one'},
  1776. files={'image': SimpleUploadedFile('test3.png', image_data)}, instance=instance)
  1777. self.assertTrue(f.is_valid())
  1778. instance = f.save()
  1779. self.assertEqual(instance.image.name, 'tests/test3.png')
  1780. self.assertEqual(instance.width, 16)
  1781. self.assertEqual(instance.height, 16)
  1782. # Editing the instance without re-uploading the image should not affect the image or its width/height properties
  1783. f = OptionalImageFileForm(
  1784. data={'description': 'New Description'},
  1785. instance=instance)
  1786. self.assertTrue(f.is_valid())
  1787. instance = f.save()
  1788. self.assertEqual(instance.description, 'New Description')
  1789. self.assertEqual(instance.image.name, 'tests/test3.png')
  1790. self.assertEqual(instance.width, 16)
  1791. self.assertEqual(instance.height, 16)
  1792. # Delete the current file since this is not done by Django.
  1793. instance.image.delete()
  1794. instance.delete()
  1795. f = OptionalImageFileForm(
  1796. data={'description': 'And a final one'},
  1797. files={'image': SimpleUploadedFile('test4.png', image_data2)}
  1798. )
  1799. self.assertTrue(f.is_valid())
  1800. instance = f.save()
  1801. self.assertEqual(instance.image.name, 'tests/test4.png')
  1802. self.assertEqual(instance.width, 48)
  1803. self.assertEqual(instance.height, 32)
  1804. instance.delete()
  1805. # Test callable upload_to behavior that's dependent on the value of another field in the model
  1806. f = ImageFileForm(
  1807. data={'description': 'And a final one', 'path': 'foo'},
  1808. files={'image': SimpleUploadedFile('test4.png', image_data)})
  1809. self.assertTrue(f.is_valid())
  1810. instance = f.save()
  1811. self.assertEqual(instance.image.name, 'foo/test4.png')
  1812. instance.delete()
  1813. class ModelOtherFieldTests(TestCase):
  1814. def test_big_integer_field(self):
  1815. bif = BigIntForm({'biggie': '-9223372036854775808'})
  1816. self.assertTrue(bif.is_valid())
  1817. bif = BigIntForm({'biggie': '-9223372036854775809'})
  1818. self.assertFalse(bif.is_valid())
  1819. self.assertEqual(bif.errors, {'biggie': ['Ensure this value is greater than or equal to -9223372036854775808.']})
  1820. bif = BigIntForm({'biggie': '9223372036854775807'})
  1821. self.assertTrue(bif.is_valid())
  1822. bif = BigIntForm({'biggie': '9223372036854775808'})
  1823. self.assertFalse(bif.is_valid())
  1824. self.assertEqual(bif.errors, {'biggie': ['Ensure this value is less than or equal to 9223372036854775807.']})
  1825. def test_comma_separated_integer_field(self):
  1826. class CommaSeparatedIntegerForm(forms.ModelForm):
  1827. class Meta:
  1828. model = CommaSeparatedInteger
  1829. fields = '__all__'
  1830. f = CommaSeparatedIntegerForm({'field': '1,2,3'})
  1831. self.assertTrue(f.is_valid())
  1832. self.assertEqual(f.cleaned_data, {'field': '1,2,3'})
  1833. f = CommaSeparatedIntegerForm({'field': '1a,2'})
  1834. self.assertEqual(f.errors, {'field': ['Enter only digits separated by commas.']})
  1835. f = CommaSeparatedIntegerForm({'field': ',,,,'})
  1836. self.assertTrue(f.is_valid())
  1837. self.assertEqual(f.cleaned_data, {'field': ',,,,'})
  1838. f = CommaSeparatedIntegerForm({'field': '1.2'})
  1839. self.assertEqual(f.errors, {'field': ['Enter only digits separated by commas.']})
  1840. f = CommaSeparatedIntegerForm({'field': '1,a,2'})
  1841. self.assertEqual(f.errors, {'field': ['Enter only digits separated by commas.']})
  1842. f = CommaSeparatedIntegerForm({'field': '1,,2'})
  1843. self.assertTrue(f.is_valid())
  1844. self.assertEqual(f.cleaned_data, {'field': '1,,2'})
  1845. f = CommaSeparatedIntegerForm({'field': '1'})
  1846. self.assertTrue(f.is_valid())
  1847. self.assertEqual(f.cleaned_data, {'field': '1'})
  1848. def test_url_on_modelform(self):
  1849. "Check basic URL field validation on model forms"
  1850. class HomepageForm(forms.ModelForm):
  1851. class Meta:
  1852. model = Homepage
  1853. fields = '__all__'
  1854. self.assertFalse(HomepageForm({'url': 'foo'}).is_valid())
  1855. self.assertFalse(HomepageForm({'url': 'http://'}).is_valid())
  1856. self.assertFalse(HomepageForm({'url': 'http://example'}).is_valid())
  1857. self.assertFalse(HomepageForm({'url': 'http://example.'}).is_valid())
  1858. self.assertFalse(HomepageForm({'url': 'http://com.'}).is_valid())
  1859. self.assertTrue(HomepageForm({'url': 'http://localhost'}).is_valid())
  1860. self.assertTrue(HomepageForm({'url': 'http://example.com'}).is_valid())
  1861. self.assertTrue(HomepageForm({'url': 'http://www.example.com'}).is_valid())
  1862. self.assertTrue(HomepageForm({'url': 'http://www.example.com:8000'}).is_valid())
  1863. self.assertTrue(HomepageForm({'url': 'http://www.example.com/test'}).is_valid())
  1864. self.assertTrue(HomepageForm({'url': 'http://www.example.com:8000/test'}).is_valid())
  1865. self.assertTrue(HomepageForm({'url': 'http://example.com/foo/bar'}).is_valid())
  1866. def test_http_prefixing(self):
  1867. """
  1868. If the http:// prefix is omitted on form input, the field adds it again. (Refs #13613)
  1869. """
  1870. class HomepageForm(forms.ModelForm):
  1871. class Meta:
  1872. model = Homepage
  1873. fields = '__all__'
  1874. form = HomepageForm({'url': 'example.com'})
  1875. self.assertTrue(form.is_valid())
  1876. self.assertEqual(form.cleaned_data['url'], 'http://example.com')
  1877. form = HomepageForm({'url': 'example.com/test'})
  1878. self.assertTrue(form.is_valid())
  1879. self.assertEqual(form.cleaned_data['url'], 'http://example.com/test')
  1880. class OtherModelFormTests(TestCase):
  1881. def test_media_on_modelform(self):
  1882. # Similar to a regular Form class you can define custom media to be used on
  1883. # the ModelForm.
  1884. f = ModelFormWithMedia()
  1885. self.assertHTMLEqual(six.text_type(f.media), '''<link href="/some/form/css" type="text/css" media="all" rel="stylesheet" />
  1886. <script type="text/javascript" src="/some/form/javascript"></script>''')
  1887. def test_choices_type(self):
  1888. # Choices on CharField and IntegerField
  1889. f = ArticleForm()
  1890. with self.assertRaises(ValidationError):
  1891. f.fields['status'].clean('42')
  1892. f = ArticleStatusForm()
  1893. with self.assertRaises(ValidationError):
  1894. f.fields['status'].clean('z')
  1895. def test_foreignkeys_which_use_to_field(self):
  1896. apple = Inventory.objects.create(barcode=86, name='Apple')
  1897. Inventory.objects.create(barcode=22, name='Pear')
  1898. core = Inventory.objects.create(barcode=87, name='Core', parent=apple)
  1899. field = forms.ModelChoiceField(Inventory.objects.all(), to_field_name='barcode')
  1900. self.assertEqual(tuple(field.choices), (
  1901. ('', '---------'),
  1902. (86, 'Apple'),
  1903. (87, 'Core'),
  1904. (22, 'Pear')))
  1905. form = InventoryForm(instance=core)
  1906. self.assertHTMLEqual(six.text_type(form['parent']), '''<select name="parent" id="id_parent">
  1907. <option value="">---------</option>
  1908. <option value="86" selected="selected">Apple</option>
  1909. <option value="87">Core</option>
  1910. <option value="22">Pear</option>
  1911. </select>''')
  1912. data = model_to_dict(core)
  1913. data['parent'] = '22'
  1914. form = InventoryForm(data=data, instance=core)
  1915. core = form.save()
  1916. self.assertEqual(core.parent.name, 'Pear')
  1917. class CategoryForm(forms.ModelForm):
  1918. description = forms.CharField()
  1919. class Meta:
  1920. model = Category
  1921. fields = ['description', 'url']
  1922. self.assertEqual(list(CategoryForm.base_fields),
  1923. ['description', 'url'])
  1924. 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>
  1925. <tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr>''')
  1926. # to_field_name should also work on ModelMultipleChoiceField ##################
  1927. field = forms.ModelMultipleChoiceField(Inventory.objects.all(), to_field_name='barcode')
  1928. self.assertEqual(tuple(field.choices), ((86, 'Apple'), (87, 'Core'), (22, 'Pear')))
  1929. self.assertQuerysetEqual(field.clean([86]), ['Apple'])
  1930. form = SelectInventoryForm({'items': [87, 22]})
  1931. self.assertTrue(form.is_valid())
  1932. self.assertEqual(len(form.cleaned_data), 1)
  1933. self.assertQuerysetEqual(form.cleaned_data['items'], ['Core', 'Pear'])
  1934. def test_model_field_that_returns_none_to_exclude_itself_with_explicit_fields(self):
  1935. self.assertEqual(list(CustomFieldForExclusionForm.base_fields),
  1936. ['name'])
  1937. self.assertHTMLEqual(six.text_type(CustomFieldForExclusionForm()),
  1938. '''<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="10" /></td></tr>''')
  1939. def test_iterable_model_m2m(self):
  1940. class ColourfulItemForm(forms.ModelForm):
  1941. class Meta:
  1942. model = ColourfulItem
  1943. fields = '__all__'
  1944. colour = Colour.objects.create(name='Blue')
  1945. form = ColourfulItemForm()
  1946. self.maxDiff = 1024
  1947. self.assertHTMLEqual(
  1948. form.as_p(),
  1949. """<p><label for="id_name">Name:</label> <input id="id_name" type="text" name="name" maxlength="50" /></p>
  1950. <p><label for="id_colours">Colours:</label> <select multiple="multiple" name="colours" id="id_colours">
  1951. <option value="%(blue_pk)s">Blue</option>
  1952. </select></p>"""
  1953. % {'blue_pk': colour.pk})
  1954. class ModelFormCustomErrorTests(TestCase):
  1955. def test_custom_error_messages(self):
  1956. data = {'name1': '@#$!!**@#$', 'name2': '@#$!!**@#$'}
  1957. errors = CustomErrorMessageForm(data).errors
  1958. self.assertHTMLEqual(
  1959. str(errors['name1']),
  1960. '<ul class="errorlist"><li>Form custom error message.</li></ul>'
  1961. )
  1962. self.assertHTMLEqual(
  1963. str(errors['name2']),
  1964. '<ul class="errorlist"><li>Model custom error message.</li></ul>'
  1965. )
  1966. def test_model_clean_error_messages(self):
  1967. data = {'name1': 'FORBIDDEN_VALUE', 'name2': 'ABC'}
  1968. form = CustomErrorMessageForm(data)
  1969. self.assertFalse(form.is_valid())
  1970. self.assertHTMLEqual(
  1971. str(form.errors['name1']),
  1972. '<ul class="errorlist"><li>Model.clean() error messages.</li></ul>'
  1973. )
  1974. data = {'name1': 'FORBIDDEN_VALUE2', 'name2': 'ABC'}
  1975. form = CustomErrorMessageForm(data)
  1976. self.assertFalse(form.is_valid())
  1977. self.assertHTMLEqual(
  1978. str(form.errors['name1']),
  1979. '<ul class="errorlist"><li>Model.clean() error messages (simpler syntax).</li></ul>'
  1980. )
  1981. data = {'name1': 'GLOBAL_ERROR', 'name2': 'ABC'}
  1982. form = CustomErrorMessageForm(data)
  1983. self.assertFalse(form.is_valid())
  1984. self.assertEqual(form.errors['__all__'], ['Global error message.'])
  1985. class CustomCleanTests(TestCase):
  1986. def test_override_clean(self):
  1987. """
  1988. Regression for #12596: Calling super from ModelForm.clean() should be
  1989. optional.
  1990. """
  1991. class TripleFormWithCleanOverride(forms.ModelForm):
  1992. class Meta:
  1993. model = Triple
  1994. fields = '__all__'
  1995. def clean(self):
  1996. if not self.cleaned_data['left'] == self.cleaned_data['right']:
  1997. raise forms.ValidationError('Left and right should be equal')
  1998. return self.cleaned_data
  1999. form = TripleFormWithCleanOverride({'left': 1, 'middle': 2, 'right': 1})
  2000. self.assertTrue(form.is_valid())
  2001. # form.instance.left will be None if the instance was not constructed
  2002. # by form.full_clean().
  2003. self.assertEqual(form.instance.left, 1)
  2004. def test_model_form_clean_applies_to_model(self):
  2005. """
  2006. Regression test for #12960. Make sure the cleaned_data returned from
  2007. ModelForm.clean() is applied to the model instance.
  2008. """
  2009. class CategoryForm(forms.ModelForm):
  2010. class Meta:
  2011. model = Category
  2012. fields = '__all__'
  2013. def clean(self):
  2014. self.cleaned_data['name'] = self.cleaned_data['name'].upper()
  2015. return self.cleaned_data
  2016. data = {'name': 'Test', 'slug': 'test', 'url': '/test'}
  2017. form = CategoryForm(data)
  2018. category = form.save()
  2019. self.assertEqual(category.name, 'TEST')
  2020. class ModelFormInheritanceTests(TestCase):
  2021. def test_form_subclass_inheritance(self):
  2022. class Form(forms.Form):
  2023. age = forms.IntegerField()
  2024. class ModelForm(forms.ModelForm, Form):
  2025. class Meta:
  2026. model = Writer
  2027. fields = '__all__'
  2028. self.assertEqual(list(ModelForm().fields.keys()), ['name', 'age'])
  2029. def test_field_removal(self):
  2030. class ModelForm(forms.ModelForm):
  2031. class Meta:
  2032. model = Writer
  2033. fields = '__all__'
  2034. class Mixin(object):
  2035. age = None
  2036. class Form(forms.Form):
  2037. age = forms.IntegerField()
  2038. class Form2(forms.Form):
  2039. foo = forms.IntegerField()
  2040. self.assertEqual(list(ModelForm().fields.keys()), ['name'])
  2041. self.assertEqual(list(type(str('NewForm'), (Mixin, Form), {})().fields.keys()), [])
  2042. self.assertEqual(list(type(str('NewForm'), (Form2, Mixin, Form), {})().fields.keys()), ['foo'])
  2043. self.assertEqual(list(type(str('NewForm'), (Mixin, ModelForm, Form), {})().fields.keys()), ['name'])
  2044. self.assertEqual(list(type(str('NewForm'), (ModelForm, Mixin, Form), {})().fields.keys()), ['name'])
  2045. self.assertEqual(list(type(str('NewForm'), (ModelForm, Form, Mixin), {})().fields.keys()), ['name', 'age'])
  2046. self.assertEqual(list(type(str('NewForm'), (ModelForm, Form), {'age': None})().fields.keys()), ['name'])
  2047. def test_field_removal_name_clashes(self):
  2048. """Regression test for https://code.djangoproject.com/ticket/22510."""
  2049. class MyForm(forms.ModelForm):
  2050. media = forms.CharField()
  2051. class Meta:
  2052. model = Writer
  2053. fields = '__all__'
  2054. class SubForm(MyForm):
  2055. media = None
  2056. self.assertIn('media', MyForm().fields)
  2057. self.assertNotIn('media', SubForm().fields)
  2058. self.assertTrue(hasattr(MyForm, 'media'))
  2059. self.assertTrue(hasattr(SubForm, 'media'))
  2060. class StumpJokeForm(forms.ModelForm):
  2061. class Meta:
  2062. model = StumpJoke
  2063. fields = '__all__'
  2064. class CustomFieldWithQuerysetButNoLimitChoicesTo(forms.Field):
  2065. queryset = 42
  2066. class StumpJokeWithCustomFieldForm(forms.ModelForm):
  2067. custom = CustomFieldWithQuerysetButNoLimitChoicesTo()
  2068. class Meta:
  2069. model = StumpJoke
  2070. fields = () # We don't need any fields from the model
  2071. class LimitChoicesToTest(TestCase):
  2072. """
  2073. Tests the functionality of ``limit_choices_to``.
  2074. """
  2075. def setUp(self):
  2076. self.threepwood = Character.objects.create(
  2077. username='threepwood',
  2078. last_action=datetime.datetime.today() + datetime.timedelta(days=1),
  2079. )
  2080. self.marley = Character.objects.create(
  2081. username='marley',
  2082. last_action=datetime.datetime.today() - datetime.timedelta(days=1),
  2083. )
  2084. def test_limit_choices_to_callable_for_fk_rel(self):
  2085. """
  2086. A ForeignKey relation can use ``limit_choices_to`` as a callable, re #2554.
  2087. """
  2088. stumpjokeform = StumpJokeForm()
  2089. self.assertIn(self.threepwood, stumpjokeform.fields['most_recently_fooled'].queryset)
  2090. self.assertNotIn(self.marley, stumpjokeform.fields['most_recently_fooled'].queryset)
  2091. def test_limit_choices_to_callable_for_m2m_rel(self):
  2092. """
  2093. A ManyToMany relation can use ``limit_choices_to`` as a callable, re #2554.
  2094. """
  2095. stumpjokeform = StumpJokeForm()
  2096. self.assertIn(self.threepwood, stumpjokeform.fields['has_fooled_today'].queryset)
  2097. self.assertNotIn(self.marley, stumpjokeform.fields['has_fooled_today'].queryset)
  2098. def test_custom_field_with_queryset_but_no_limit_choices_to(self):
  2099. """
  2100. Regression test for #23795: Make sure a custom field with a `queryset`
  2101. attribute but no `limit_choices_to` still works.
  2102. """
  2103. f = StumpJokeWithCustomFieldForm()
  2104. self.assertEqual(f.fields['custom'].queryset, 42)
  2105. class FormFieldCallbackTests(TestCase):
  2106. def test_baseform_with_widgets_in_meta(self):
  2107. """Regression for #13095: Using base forms with widgets defined in Meta should not raise errors."""
  2108. widget = forms.Textarea()
  2109. class BaseForm(forms.ModelForm):
  2110. class Meta:
  2111. model = Person
  2112. widgets = {'name': widget}
  2113. fields = "__all__"
  2114. Form = modelform_factory(Person, form=BaseForm)
  2115. self.assertIs(Form.base_fields['name'].widget, widget)
  2116. def test_factory_with_widget_argument(self):
  2117. """ Regression for #15315: modelform_factory should accept widgets
  2118. argument
  2119. """
  2120. widget = forms.Textarea()
  2121. # Without a widget should not set the widget to textarea
  2122. Form = modelform_factory(Person, fields="__all__")
  2123. self.assertNotEqual(Form.base_fields['name'].widget.__class__, forms.Textarea)
  2124. # With a widget should not set the widget to textarea
  2125. Form = modelform_factory(Person, fields="__all__", widgets={'name': widget})
  2126. self.assertEqual(Form.base_fields['name'].widget.__class__, forms.Textarea)
  2127. def test_modelform_factory_without_fields(self):
  2128. """ Regression for #19733 """
  2129. message = (
  2130. "Calling modelform_factory without defining 'fields' or 'exclude' "
  2131. "explicitly is prohibited."
  2132. )
  2133. with self.assertRaisesMessage(ImproperlyConfigured, message):
  2134. modelform_factory(Person)
  2135. def test_modelform_factory_with_all_fields(self):
  2136. """ Regression for #19733 """
  2137. form = modelform_factory(Person, fields="__all__")
  2138. self.assertEqual(list(form.base_fields), ["name"])
  2139. def test_custom_callback(self):
  2140. """Test that a custom formfield_callback is used if provided"""
  2141. callback_args = []
  2142. def callback(db_field, **kwargs):
  2143. callback_args.append((db_field, kwargs))
  2144. return db_field.formfield(**kwargs)
  2145. widget = forms.Textarea()
  2146. class BaseForm(forms.ModelForm):
  2147. class Meta:
  2148. model = Person
  2149. widgets = {'name': widget}
  2150. fields = "__all__"
  2151. modelform_factory(Person, form=BaseForm, formfield_callback=callback)
  2152. id_field, name_field = Person._meta.fields
  2153. self.assertEqual(callback_args,
  2154. [(id_field, {}), (name_field, {'widget': widget})])
  2155. def test_bad_callback(self):
  2156. # A bad callback provided by user still gives an error
  2157. self.assertRaises(TypeError, modelform_factory, Person, fields="__all__",
  2158. formfield_callback='not a function or callable')
  2159. class LocalizedModelFormTest(TestCase):
  2160. def test_model_form_applies_localize_to_some_fields(self):
  2161. class PartiallyLocalizedTripleForm(forms.ModelForm):
  2162. class Meta:
  2163. model = Triple
  2164. localized_fields = ('left', 'right',)
  2165. fields = '__all__'
  2166. f = PartiallyLocalizedTripleForm({'left': 10, 'middle': 10, 'right': 10})
  2167. self.assertTrue(f.is_valid())
  2168. self.assertTrue(f.fields['left'].localize)
  2169. self.assertFalse(f.fields['middle'].localize)
  2170. self.assertTrue(f.fields['right'].localize)
  2171. def test_model_form_applies_localize_to_all_fields(self):
  2172. class FullyLocalizedTripleForm(forms.ModelForm):
  2173. class Meta:
  2174. model = Triple
  2175. localized_fields = '__all__'
  2176. fields = '__all__'
  2177. f = FullyLocalizedTripleForm({'left': 10, 'middle': 10, 'right': 10})
  2178. self.assertTrue(f.is_valid())
  2179. self.assertTrue(f.fields['left'].localize)
  2180. self.assertTrue(f.fields['middle'].localize)
  2181. self.assertTrue(f.fields['right'].localize)
  2182. def test_model_form_refuses_arbitrary_string(self):
  2183. with self.assertRaises(TypeError):
  2184. class BrokenLocalizedTripleForm(forms.ModelForm):
  2185. class Meta:
  2186. model = Triple
  2187. localized_fields = "foo"
  2188. class CustomMetaclass(ModelFormMetaclass):
  2189. def __new__(cls, name, bases, attrs):
  2190. new = super(CustomMetaclass, cls).__new__(cls, name, bases, attrs)
  2191. new.base_fields = {}
  2192. return new
  2193. class CustomMetaclassForm(six.with_metaclass(CustomMetaclass, forms.ModelForm)):
  2194. pass
  2195. class CustomMetaclassTestCase(TestCase):
  2196. def test_modelform_factory_metaclass(self):
  2197. new_cls = modelform_factory(Person, fields="__all__", form=CustomMetaclassForm)
  2198. self.assertEqual(new_cls.base_fields, {})