tests.py 116 KB

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