tests.py 117 KB

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