tests.py 130 KB

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