tests.py 115 KB

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