tests.py 122 KB

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