tests.py 98 KB

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