tests.py 133 KB

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