tests.py 114 KB

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