tests.py 100 KB

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