tests.py 121 KB

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