tests.py 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520
  1. from __future__ import unicode_literals
  2. from datetime import date
  3. import warnings
  4. from django import forms
  5. from django.contrib.admin.options import (ModelAdmin, TabularInline,
  6. HORIZONTAL, VERTICAL)
  7. from django.contrib.admin.sites import AdminSite
  8. from django.contrib.admin.widgets import AdminDateWidget, AdminRadioSelect
  9. from django.contrib.admin.validation import ModelAdminValidator
  10. from django.contrib.admin import (SimpleListFilter,
  11. BooleanFieldListFilter)
  12. from django.core.checks import Error
  13. from django.core.exceptions import ImproperlyConfigured
  14. from django.forms.models import BaseModelFormSet
  15. from django.forms.widgets import Select
  16. from django.test import TestCase
  17. from django.utils import six
  18. from django.utils.deprecation import RemovedInDjango19Warning
  19. from .models import Band, Concert, ValidationTestModel, ValidationTestInlineModel
  20. class MockRequest(object):
  21. pass
  22. class MockSuperUser(object):
  23. def has_perm(self, perm):
  24. return True
  25. request = MockRequest()
  26. request.user = MockSuperUser()
  27. class ModelAdminTests(TestCase):
  28. def setUp(self):
  29. self.band = Band.objects.create(
  30. name='The Doors',
  31. bio='',
  32. sign_date=date(1965, 1, 1),
  33. )
  34. self.site = AdminSite()
  35. # form/fields/fieldsets interaction ##############################
  36. def test_default_fields(self):
  37. ma = ModelAdmin(Band, self.site)
  38. self.assertEqual(list(ma.get_form(request).base_fields),
  39. ['name', 'bio', 'sign_date'])
  40. self.assertEqual(list(ma.get_fields(request)),
  41. ['name', 'bio', 'sign_date'])
  42. self.assertEqual(list(ma.get_fields(request, self.band)),
  43. ['name', 'bio', 'sign_date'])
  44. def test_default_fieldsets(self):
  45. # fieldsets_add and fieldsets_change should return a special data structure that
  46. # is used in the templates. They should generate the "right thing" whether we
  47. # have specified a custom form, the fields argument, or nothing at all.
  48. #
  49. # Here's the default case. There are no custom form_add/form_change methods,
  50. # no fields argument, and no fieldsets argument.
  51. ma = ModelAdmin(Band, self.site)
  52. self.assertEqual(ma.get_fieldsets(request),
  53. [(None, {'fields': ['name', 'bio', 'sign_date']})])
  54. self.assertEqual(ma.get_fieldsets(request, self.band),
  55. [(None, {'fields': ['name', 'bio', 'sign_date']})])
  56. def test_get_fieldsets(self):
  57. # Test that get_fieldsets is called when figuring out form fields.
  58. # Refs #18681.
  59. class BandAdmin(ModelAdmin):
  60. def get_fieldsets(self, request, obj=None):
  61. return [(None, {'fields': ['name', 'bio']})]
  62. ma = BandAdmin(Band, self.site)
  63. form = ma.get_form(None)
  64. self.assertEqual(form._meta.fields, ['name', 'bio'])
  65. class InlineBandAdmin(TabularInline):
  66. model = Concert
  67. fk_name = 'main_band'
  68. can_delete = False
  69. def get_fieldsets(self, request, obj=None):
  70. return [(None, {'fields': ['day', 'transport']})]
  71. ma = InlineBandAdmin(Band, self.site)
  72. form = ma.get_formset(None).form
  73. self.assertEqual(form._meta.fields, ['day', 'transport'])
  74. def test_lookup_allowed_allows_nonexistent_lookup(self):
  75. """
  76. Ensure that a lookup_allowed allows a parameter
  77. whose field lookup doesn't exist.
  78. Refs #21129.
  79. """
  80. class BandAdmin(ModelAdmin):
  81. fields = ['name']
  82. ma = BandAdmin(Band, self.site)
  83. self.assertTrue(ma.lookup_allowed('name__nonexistent', 'test_value'))
  84. def test_field_arguments(self):
  85. # If we specify the fields argument, fieldsets_add and fielsets_change should
  86. # just stick the fields into a formsets structure and return it.
  87. class BandAdmin(ModelAdmin):
  88. fields = ['name']
  89. ma = BandAdmin(Band, self.site)
  90. self.assertEqual(list(ma.get_fields(request)), ['name'])
  91. self.assertEqual(list(ma.get_fields(request, self.band)), ['name'])
  92. self.assertEqual(ma.get_fieldsets(request),
  93. [(None, {'fields': ['name']})])
  94. self.assertEqual(ma.get_fieldsets(request, self.band),
  95. [(None, {'fields': ['name']})])
  96. def test_field_arguments_restricted_on_form(self):
  97. # If we specify fields or fieldsets, it should exclude fields on the Form class
  98. # to the fields specified. This may cause errors to be raised in the db layer if
  99. # required model fields aren't in fields/fieldsets, but that's preferable to
  100. # ghost errors where you have a field in your Form class that isn't being
  101. # displayed because you forgot to add it to fields/fieldsets
  102. # Using `fields`.
  103. class BandAdmin(ModelAdmin):
  104. fields = ['name']
  105. ma = BandAdmin(Band, self.site)
  106. self.assertEqual(list(ma.get_form(request).base_fields), ['name'])
  107. self.assertEqual(list(ma.get_form(request, self.band).base_fields),
  108. ['name'])
  109. # Using `fieldsets`.
  110. class BandAdmin(ModelAdmin):
  111. fieldsets = [(None, {'fields': ['name']})]
  112. ma = BandAdmin(Band, self.site)
  113. self.assertEqual(list(ma.get_form(request).base_fields), ['name'])
  114. self.assertEqual(list(ma.get_form(request, self.band).base_fields),
  115. ['name'])
  116. # Using `exclude`.
  117. class BandAdmin(ModelAdmin):
  118. exclude = ['bio']
  119. ma = BandAdmin(Band, self.site)
  120. self.assertEqual(list(ma.get_form(request).base_fields),
  121. ['name', 'sign_date'])
  122. # You can also pass a tuple to `exclude`.
  123. class BandAdmin(ModelAdmin):
  124. exclude = ('bio',)
  125. ma = BandAdmin(Band, self.site)
  126. self.assertEqual(list(ma.get_form(request).base_fields),
  127. ['name', 'sign_date'])
  128. # Using `fields` and `exclude`.
  129. class BandAdmin(ModelAdmin):
  130. fields = ['name', 'bio']
  131. exclude = ['bio']
  132. ma = BandAdmin(Band, self.site)
  133. self.assertEqual(list(ma.get_form(request).base_fields),
  134. ['name'])
  135. def test_custom_form_meta_exclude_with_readonly(self):
  136. """
  137. Ensure that the custom ModelForm's `Meta.exclude` is respected when
  138. used in conjunction with `ModelAdmin.readonly_fields` and when no
  139. `ModelAdmin.exclude` is defined.
  140. Refs #14496.
  141. """
  142. # First, with `ModelAdmin` -----------------------
  143. class AdminBandForm(forms.ModelForm):
  144. class Meta:
  145. model = Band
  146. exclude = ['bio']
  147. class BandAdmin(ModelAdmin):
  148. readonly_fields = ['name']
  149. form = AdminBandForm
  150. ma = BandAdmin(Band, self.site)
  151. self.assertEqual(list(ma.get_form(request).base_fields),
  152. ['sign_date'])
  153. # Then, with `InlineModelAdmin` -----------------
  154. class AdminConcertForm(forms.ModelForm):
  155. class Meta:
  156. model = Concert
  157. exclude = ['day']
  158. class ConcertInline(TabularInline):
  159. readonly_fields = ['transport']
  160. form = AdminConcertForm
  161. fk_name = 'main_band'
  162. model = Concert
  163. class BandAdmin(ModelAdmin):
  164. inlines = [
  165. ConcertInline
  166. ]
  167. ma = BandAdmin(Band, self.site)
  168. self.assertEqual(
  169. list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields),
  170. ['main_band', 'opening_band', 'id', 'DELETE'])
  171. def test_custom_form_meta_exclude(self):
  172. """
  173. Ensure that the custom ModelForm's `Meta.exclude` is overridden if
  174. `ModelAdmin.exclude` or `InlineModelAdmin.exclude` are defined.
  175. Refs #14496.
  176. """
  177. # First, with `ModelAdmin` -----------------------
  178. class AdminBandForm(forms.ModelForm):
  179. class Meta:
  180. model = Band
  181. exclude = ['bio']
  182. class BandAdmin(ModelAdmin):
  183. exclude = ['name']
  184. form = AdminBandForm
  185. ma = BandAdmin(Band, self.site)
  186. self.assertEqual(list(ma.get_form(request).base_fields),
  187. ['bio', 'sign_date'])
  188. # Then, with `InlineModelAdmin` -----------------
  189. class AdminConcertForm(forms.ModelForm):
  190. class Meta:
  191. model = Concert
  192. exclude = ['day']
  193. class ConcertInline(TabularInline):
  194. exclude = ['transport']
  195. form = AdminConcertForm
  196. fk_name = 'main_band'
  197. model = Concert
  198. class BandAdmin(ModelAdmin):
  199. inlines = [
  200. ConcertInline
  201. ]
  202. ma = BandAdmin(Band, self.site)
  203. self.assertEqual(
  204. list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields),
  205. ['main_band', 'opening_band', 'day', 'id', 'DELETE'])
  206. def test_custom_form_validation(self):
  207. # If we specify a form, it should use it allowing custom validation to work
  208. # properly. This won't, however, break any of the admin widgets or media.
  209. class AdminBandForm(forms.ModelForm):
  210. delete = forms.BooleanField()
  211. class BandAdmin(ModelAdmin):
  212. form = AdminBandForm
  213. ma = BandAdmin(Band, self.site)
  214. self.assertEqual(list(ma.get_form(request).base_fields),
  215. ['name', 'bio', 'sign_date', 'delete'])
  216. self.assertEqual(
  217. type(ma.get_form(request).base_fields['sign_date'].widget),
  218. AdminDateWidget)
  219. def test_form_exclude_kwarg_override(self):
  220. """
  221. Ensure that the `exclude` kwarg passed to `ModelAdmin.get_form()`
  222. overrides all other declarations. Refs #8999.
  223. """
  224. class AdminBandForm(forms.ModelForm):
  225. class Meta:
  226. model = Band
  227. exclude = ['name']
  228. class BandAdmin(ModelAdmin):
  229. exclude = ['sign_date']
  230. form = AdminBandForm
  231. def get_form(self, request, obj=None, **kwargs):
  232. kwargs['exclude'] = ['bio']
  233. return super(BandAdmin, self).get_form(request, obj, **kwargs)
  234. ma = BandAdmin(Band, self.site)
  235. self.assertEqual(list(ma.get_form(request).base_fields),
  236. ['name', 'sign_date'])
  237. def test_formset_exclude_kwarg_override(self):
  238. """
  239. Ensure that the `exclude` kwarg passed to `InlineModelAdmin.get_formset()`
  240. overrides all other declarations. Refs #8999.
  241. """
  242. class AdminConcertForm(forms.ModelForm):
  243. class Meta:
  244. model = Concert
  245. exclude = ['day']
  246. class ConcertInline(TabularInline):
  247. exclude = ['transport']
  248. form = AdminConcertForm
  249. fk_name = 'main_band'
  250. model = Concert
  251. def get_formset(self, request, obj=None, **kwargs):
  252. kwargs['exclude'] = ['opening_band']
  253. return super(ConcertInline, self).get_formset(request, obj, **kwargs)
  254. class BandAdmin(ModelAdmin):
  255. inlines = [
  256. ConcertInline
  257. ]
  258. ma = BandAdmin(Band, self.site)
  259. self.assertEqual(
  260. list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields),
  261. ['main_band', 'day', 'transport', 'id', 'DELETE'])
  262. def test_queryset_override(self):
  263. # If we need to override the queryset of a ModelChoiceField in our custom form
  264. # make sure that RelatedFieldWidgetWrapper doesn't mess that up.
  265. band2 = Band(name='The Beatles', bio='', sign_date=date(1962, 1, 1))
  266. band2.save()
  267. class ConcertAdmin(ModelAdmin):
  268. pass
  269. ma = ConcertAdmin(Concert, self.site)
  270. form = ma.get_form(request)()
  271. self.assertHTMLEqual(str(form["main_band"]),
  272. '<select name="main_band" id="id_main_band">\n'
  273. '<option value="" selected="selected">---------</option>\n'
  274. '<option value="%d">The Beatles</option>\n'
  275. '<option value="%d">The Doors</option>\n'
  276. '</select>' % (band2.id, self.band.id))
  277. class AdminConcertForm(forms.ModelForm):
  278. pass
  279. def __init__(self, *args, **kwargs):
  280. super(AdminConcertForm, self).__init__(*args, **kwargs)
  281. self.fields["main_band"].queryset = Band.objects.filter(name='The Doors')
  282. class ConcertAdmin(ModelAdmin):
  283. form = AdminConcertForm
  284. ma = ConcertAdmin(Concert, self.site)
  285. form = ma.get_form(request)()
  286. self.assertHTMLEqual(str(form["main_band"]),
  287. '<select name="main_band" id="id_main_band">\n'
  288. '<option value="" selected="selected">---------</option>\n'
  289. '<option value="%d">The Doors</option>\n'
  290. '</select>' % self.band.id)
  291. def test_regression_for_ticket_15820(self):
  292. """
  293. Ensure that `obj` is passed from `InlineModelAdmin.get_fieldsets()` to
  294. `InlineModelAdmin.get_formset()`.
  295. """
  296. class CustomConcertForm(forms.ModelForm):
  297. class Meta:
  298. model = Concert
  299. fields = ['day']
  300. class ConcertInline(TabularInline):
  301. model = Concert
  302. fk_name = 'main_band'
  303. def get_formset(self, request, obj=None, **kwargs):
  304. if obj:
  305. kwargs['form'] = CustomConcertForm
  306. return super(ConcertInline, self).get_formset(request, obj, **kwargs)
  307. class BandAdmin(ModelAdmin):
  308. inlines = [
  309. ConcertInline
  310. ]
  311. Concert.objects.create(main_band=self.band, opening_band=self.band, day=1)
  312. ma = BandAdmin(Band, self.site)
  313. inline_instances = ma.get_inline_instances(request)
  314. fieldsets = list(inline_instances[0].get_fieldsets(request))
  315. self.assertEqual(fieldsets[0][1]['fields'], ['main_band', 'opening_band', 'day', 'transport'])
  316. fieldsets = list(inline_instances[0].get_fieldsets(request, inline_instances[0].model))
  317. self.assertEqual(fieldsets[0][1]['fields'], ['day'])
  318. # radio_fields behavior ###########################################
  319. def test_default_foreign_key_widget(self):
  320. # First, without any radio_fields specified, the widgets for ForeignKey
  321. # and fields with choices specified ought to be a basic Select widget.
  322. # ForeignKey widgets in the admin are wrapped with RelatedFieldWidgetWrapper so
  323. # they need to be handled properly when type checking. For Select fields, all of
  324. # the choices lists have a first entry of dashes.
  325. cma = ModelAdmin(Concert, self.site)
  326. cmafa = cma.get_form(request)
  327. self.assertEqual(type(cmafa.base_fields['main_band'].widget.widget),
  328. Select)
  329. self.assertEqual(
  330. list(cmafa.base_fields['main_band'].widget.choices),
  331. [('', '---------'), (self.band.id, 'The Doors')])
  332. self.assertEqual(
  333. type(cmafa.base_fields['opening_band'].widget.widget), Select)
  334. self.assertEqual(
  335. list(cmafa.base_fields['opening_band'].widget.choices),
  336. [('', '---------'), (self.band.id, 'The Doors')])
  337. self.assertEqual(type(cmafa.base_fields['day'].widget), Select)
  338. self.assertEqual(list(cmafa.base_fields['day'].widget.choices),
  339. [('', '---------'), (1, 'Fri'), (2, 'Sat')])
  340. self.assertEqual(type(cmafa.base_fields['transport'].widget),
  341. Select)
  342. self.assertEqual(
  343. list(cmafa.base_fields['transport'].widget.choices),
  344. [('', '---------'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')])
  345. def test_foreign_key_as_radio_field(self):
  346. # Now specify all the fields as radio_fields. Widgets should now be
  347. # RadioSelect, and the choices list should have a first entry of 'None' if
  348. # blank=True for the model field. Finally, the widget should have the
  349. # 'radiolist' attr, and 'inline' as well if the field is specified HORIZONTAL.
  350. class ConcertAdmin(ModelAdmin):
  351. radio_fields = {
  352. 'main_band': HORIZONTAL,
  353. 'opening_band': VERTICAL,
  354. 'day': VERTICAL,
  355. 'transport': HORIZONTAL,
  356. }
  357. cma = ConcertAdmin(Concert, self.site)
  358. cmafa = cma.get_form(request)
  359. self.assertEqual(type(cmafa.base_fields['main_band'].widget.widget),
  360. AdminRadioSelect)
  361. self.assertEqual(cmafa.base_fields['main_band'].widget.attrs,
  362. {'class': 'radiolist inline'})
  363. self.assertEqual(list(cmafa.base_fields['main_band'].widget.choices),
  364. [(self.band.id, 'The Doors')])
  365. self.assertEqual(
  366. type(cmafa.base_fields['opening_band'].widget.widget),
  367. AdminRadioSelect)
  368. self.assertEqual(cmafa.base_fields['opening_band'].widget.attrs,
  369. {'class': 'radiolist'})
  370. self.assertEqual(
  371. list(cmafa.base_fields['opening_band'].widget.choices),
  372. [('', 'None'), (self.band.id, 'The Doors')])
  373. self.assertEqual(type(cmafa.base_fields['day'].widget),
  374. AdminRadioSelect)
  375. self.assertEqual(cmafa.base_fields['day'].widget.attrs,
  376. {'class': 'radiolist'})
  377. self.assertEqual(list(cmafa.base_fields['day'].widget.choices),
  378. [(1, 'Fri'), (2, 'Sat')])
  379. self.assertEqual(type(cmafa.base_fields['transport'].widget),
  380. AdminRadioSelect)
  381. self.assertEqual(cmafa.base_fields['transport'].widget.attrs,
  382. {'class': 'radiolist inline'})
  383. self.assertEqual(list(cmafa.base_fields['transport'].widget.choices),
  384. [('', 'None'), (1, 'Plane'), (2, 'Train'), (3, 'Bus')])
  385. class AdminConcertForm(forms.ModelForm):
  386. class Meta:
  387. model = Concert
  388. exclude = ('transport',)
  389. class ConcertAdmin(ModelAdmin):
  390. form = AdminConcertForm
  391. ma = ConcertAdmin(Concert, self.site)
  392. self.assertEqual(list(ma.get_form(request).base_fields),
  393. ['main_band', 'opening_band', 'day'])
  394. class AdminConcertForm(forms.ModelForm):
  395. extra = forms.CharField()
  396. class Meta:
  397. model = Concert
  398. fields = ['extra', 'transport']
  399. class ConcertAdmin(ModelAdmin):
  400. form = AdminConcertForm
  401. ma = ConcertAdmin(Concert, self.site)
  402. self.assertEqual(list(ma.get_form(request).base_fields),
  403. ['extra', 'transport'])
  404. class ConcertInline(TabularInline):
  405. form = AdminConcertForm
  406. model = Concert
  407. fk_name = 'main_band'
  408. can_delete = True
  409. class BandAdmin(ModelAdmin):
  410. inlines = [
  411. ConcertInline
  412. ]
  413. ma = BandAdmin(Band, self.site)
  414. self.assertEqual(
  415. list(list(ma.get_formsets_with_inlines(request))[0][0]().forms[0].fields),
  416. ['extra', 'transport', 'id', 'DELETE', 'main_band'])
  417. class CheckTestCase(TestCase):
  418. def assertIsInvalid(self, model_admin, model, msg,
  419. id=None, hint=None, invalid_obj=None):
  420. invalid_obj = invalid_obj or model_admin
  421. errors = model_admin.check(model=model)
  422. expected = [
  423. Error(
  424. msg,
  425. hint=hint,
  426. obj=invalid_obj,
  427. id=id,
  428. )
  429. ]
  430. self.assertEqual(errors, expected)
  431. def assertIsInvalidRegexp(self, model_admin, model, msg,
  432. id=None, hint=None, invalid_obj=None):
  433. """
  434. Same as assertIsInvalid but treats the given msg as a regexp.
  435. """
  436. invalid_obj = invalid_obj or model_admin
  437. errors = model_admin.check(model=model)
  438. self.assertEqual(len(errors), 1)
  439. error = errors[0]
  440. self.assertEqual(error.hint, hint)
  441. self.assertEqual(error.obj, invalid_obj)
  442. self.assertEqual(error.id, id)
  443. six.assertRegex(self, error.msg, msg)
  444. def assertIsValid(self, model_admin, model):
  445. errors = model_admin.check(model=model)
  446. expected = []
  447. self.assertEqual(errors, expected)
  448. class RawIdCheckTests(CheckTestCase):
  449. def test_not_iterable(self):
  450. class ValidationTestModelAdmin(ModelAdmin):
  451. raw_id_fields = 10
  452. self.assertIsInvalid(
  453. ValidationTestModelAdmin, ValidationTestModel,
  454. "The value of 'raw_id_fields' must be a list or tuple.",
  455. 'admin.E001')
  456. def test_missing_field(self):
  457. class ValidationTestModelAdmin(ModelAdmin):
  458. raw_id_fields = ('non_existent_field',)
  459. self.assertIsInvalid(
  460. ValidationTestModelAdmin, ValidationTestModel,
  461. ("The value of 'raw_id_fields[0]' refers to 'non_existent_field', "
  462. "which is not an attribute of 'modeladmin.ValidationTestModel'."),
  463. 'admin.E002')
  464. def test_invalid_field_type(self):
  465. class ValidationTestModelAdmin(ModelAdmin):
  466. raw_id_fields = ('name',)
  467. self.assertIsInvalid(
  468. ValidationTestModelAdmin, ValidationTestModel,
  469. "The value of 'raw_id_fields[0]' must be a ForeignKey or ManyToManyField.",
  470. 'admin.E003')
  471. def test_valid_case(self):
  472. class ValidationTestModelAdmin(ModelAdmin):
  473. raw_id_fields = ('users',)
  474. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  475. class FieldsetsCheckTests(CheckTestCase):
  476. def test_valid_case(self):
  477. class ValidationTestModelAdmin(ModelAdmin):
  478. fieldsets = (("General", {'fields': ('name',)}),)
  479. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  480. def test_not_iterable(self):
  481. class ValidationTestModelAdmin(ModelAdmin):
  482. fieldsets = 10
  483. self.assertIsInvalid(
  484. ValidationTestModelAdmin, ValidationTestModel,
  485. "The value of 'fieldsets' must be a list or tuple.",
  486. 'admin.E007')
  487. def test_non_iterable_item(self):
  488. class ValidationTestModelAdmin(ModelAdmin):
  489. fieldsets = ({},)
  490. self.assertIsInvalid(
  491. ValidationTestModelAdmin, ValidationTestModel,
  492. "The value of 'fieldsets[0]' must be a list or tuple.",
  493. 'admin.E008')
  494. def test_item_not_a_pair(self):
  495. class ValidationTestModelAdmin(ModelAdmin):
  496. fieldsets = ((),)
  497. self.assertIsInvalid(
  498. ValidationTestModelAdmin, ValidationTestModel,
  499. "The value of 'fieldsets[0]' must be of length 2.",
  500. 'admin.E009')
  501. def test_second_element_of_item_not_a_dict(self):
  502. class ValidationTestModelAdmin(ModelAdmin):
  503. fieldsets = (("General", ()),)
  504. self.assertIsInvalid(
  505. ValidationTestModelAdmin, ValidationTestModel,
  506. "The value of 'fieldsets[0][1]' must be a dictionary.",
  507. 'admin.E010')
  508. def test_missing_fields_key(self):
  509. class ValidationTestModelAdmin(ModelAdmin):
  510. fieldsets = (("General", {}),)
  511. self.assertIsInvalid(
  512. ValidationTestModelAdmin, ValidationTestModel,
  513. "The value of 'fieldsets[0][1]' must contain the key 'fields'.",
  514. 'admin.E011')
  515. class ValidationTestModelAdmin(ModelAdmin):
  516. fieldsets = (("General", {'fields': ('name',)}),)
  517. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  518. def test_specified_both_fields_and_fieldsets(self):
  519. class ValidationTestModelAdmin(ModelAdmin):
  520. fieldsets = (("General", {'fields': ('name',)}),)
  521. fields = ['name']
  522. self.assertIsInvalid(
  523. ValidationTestModelAdmin, ValidationTestModel,
  524. "Both 'fieldsets' and 'fields' are specified.",
  525. 'admin.E005')
  526. def test_duplicate_fields(self):
  527. class ValidationTestModelAdmin(ModelAdmin):
  528. fieldsets = [(None, {'fields': ['name', 'name']})]
  529. self.assertIsInvalid(
  530. ValidationTestModelAdmin, ValidationTestModel,
  531. "There are duplicate field(s) in 'fieldsets[0][1]'.",
  532. 'admin.E012')
  533. def test_fieldsets_with_custom_form_validation(self):
  534. class BandAdmin(ModelAdmin):
  535. fieldsets = (
  536. ('Band', {
  537. 'fields': ('name',)
  538. }),
  539. )
  540. self.assertIsValid(BandAdmin, Band)
  541. class FieldsCheckTests(CheckTestCase):
  542. def test_duplicate_fields_in_fields(self):
  543. class ValidationTestModelAdmin(ModelAdmin):
  544. fields = ['name', 'name']
  545. self.assertIsInvalid(
  546. ValidationTestModelAdmin, ValidationTestModel,
  547. "The value of 'fields' contains duplicate field(s).",
  548. 'admin.E006')
  549. def test_inline(self):
  550. class ValidationTestInline(TabularInline):
  551. model = ValidationTestInlineModel
  552. fields = 10
  553. class ValidationTestModelAdmin(ModelAdmin):
  554. inlines = [ValidationTestInline]
  555. self.assertIsInvalid(
  556. ValidationTestModelAdmin, ValidationTestModel,
  557. "The value of 'fields' must be a list or tuple.",
  558. 'admin.E004',
  559. invalid_obj=ValidationTestInline)
  560. class FormCheckTests(CheckTestCase):
  561. def test_invalid_type(self):
  562. class FakeForm(object):
  563. pass
  564. class ValidationTestModelAdmin(ModelAdmin):
  565. form = FakeForm
  566. self.assertIsInvalid(
  567. ValidationTestModelAdmin, ValidationTestModel,
  568. "The value of 'form' must inherit from 'BaseModelForm'.",
  569. 'admin.E016')
  570. def test_fieldsets_with_custom_form_validation(self):
  571. class BandAdmin(ModelAdmin):
  572. fieldsets = (
  573. ('Band', {
  574. 'fields': ('name',)
  575. }),
  576. )
  577. self.assertIsValid(BandAdmin, Band)
  578. def test_valid_case(self):
  579. class AdminBandForm(forms.ModelForm):
  580. delete = forms.BooleanField()
  581. class BandAdmin(ModelAdmin):
  582. form = AdminBandForm
  583. fieldsets = (
  584. ('Band', {
  585. 'fields': ('name', 'bio', 'sign_date', 'delete')
  586. }),
  587. )
  588. self.assertIsValid(BandAdmin, Band)
  589. class FilterVerticalCheckTests(CheckTestCase):
  590. def test_not_iterable(self):
  591. class ValidationTestModelAdmin(ModelAdmin):
  592. filter_vertical = 10
  593. self.assertIsInvalid(
  594. ValidationTestModelAdmin, ValidationTestModel,
  595. "The value of 'filter_vertical' must be a list or tuple.",
  596. 'admin.E017')
  597. def test_missing_field(self):
  598. class ValidationTestModelAdmin(ModelAdmin):
  599. filter_vertical = ('non_existent_field',)
  600. self.assertIsInvalid(
  601. ValidationTestModelAdmin, ValidationTestModel,
  602. ("The value of 'filter_vertical[0]' refers to 'non_existent_field', "
  603. "which is not an attribute of 'modeladmin.ValidationTestModel'."),
  604. 'admin.E019')
  605. def test_invalid_field_type(self):
  606. class ValidationTestModelAdmin(ModelAdmin):
  607. filter_vertical = ('name',)
  608. self.assertIsInvalid(
  609. ValidationTestModelAdmin, ValidationTestModel,
  610. "The value of 'filter_vertical[0]' must be a ManyToManyField.",
  611. 'admin.E020')
  612. def test_valid_case(self):
  613. class ValidationTestModelAdmin(ModelAdmin):
  614. filter_vertical = ("users",)
  615. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  616. class FilterHorizontalCheckTests(CheckTestCase):
  617. def test_not_iterable(self):
  618. class ValidationTestModelAdmin(ModelAdmin):
  619. filter_horizontal = 10
  620. self.assertIsInvalid(
  621. ValidationTestModelAdmin, ValidationTestModel,
  622. "The value of 'filter_horizontal' must be a list or tuple.",
  623. 'admin.E018')
  624. def test_missing_field(self):
  625. class ValidationTestModelAdmin(ModelAdmin):
  626. filter_horizontal = ('non_existent_field',)
  627. self.assertIsInvalid(
  628. ValidationTestModelAdmin, ValidationTestModel,
  629. ("The value of 'filter_horizontal[0]' refers to 'non_existent_field', "
  630. "which is not an attribute of 'modeladmin.ValidationTestModel'."),
  631. 'admin.E019')
  632. def test_invalid_field_type(self):
  633. class ValidationTestModelAdmin(ModelAdmin):
  634. filter_horizontal = ('name',)
  635. self.assertIsInvalid(
  636. ValidationTestModelAdmin, ValidationTestModel,
  637. "The value of 'filter_horizontal[0]' must be a ManyToManyField.",
  638. 'admin.E020')
  639. def test_valid_case(self):
  640. class ValidationTestModelAdmin(ModelAdmin):
  641. filter_horizontal = ("users",)
  642. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  643. class RadioFieldsCheckTests(CheckTestCase):
  644. def test_not_dictionary(self):
  645. class ValidationTestModelAdmin(ModelAdmin):
  646. radio_fields = ()
  647. self.assertIsInvalid(
  648. ValidationTestModelAdmin, ValidationTestModel,
  649. "The value of 'radio_fields' must be a dictionary.",
  650. 'admin.E021')
  651. def test_missing_field(self):
  652. class ValidationTestModelAdmin(ModelAdmin):
  653. radio_fields = {'non_existent_field': VERTICAL}
  654. self.assertIsInvalid(
  655. ValidationTestModelAdmin, ValidationTestModel,
  656. ("The value of 'radio_fields' refers to 'non_existent_field', "
  657. "which is not an attribute of 'modeladmin.ValidationTestModel'."),
  658. 'admin.E022')
  659. def test_invalid_field_type(self):
  660. class ValidationTestModelAdmin(ModelAdmin):
  661. radio_fields = {'name': VERTICAL}
  662. self.assertIsInvalid(
  663. ValidationTestModelAdmin, ValidationTestModel,
  664. ("The value of 'radio_fields' refers to 'name', which is not an instance "
  665. "of ForeignKey, and does not have a 'choices' definition."),
  666. 'admin.E023')
  667. def test_invalid_value(self):
  668. class ValidationTestModelAdmin(ModelAdmin):
  669. radio_fields = {"state": None}
  670. self.assertIsInvalid(
  671. ValidationTestModelAdmin, ValidationTestModel,
  672. "The value of 'radio_fields[\"state\"]' must be either admin.HORIZONTAL or admin.VERTICAL.",
  673. 'admin.E024')
  674. def test_valid_case(self):
  675. class ValidationTestModelAdmin(ModelAdmin):
  676. radio_fields = {"state": VERTICAL}
  677. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  678. class PrepopulatedFieldsCheckTests(CheckTestCase):
  679. def test_not_dictionary(self):
  680. class ValidationTestModelAdmin(ModelAdmin):
  681. prepopulated_fields = ()
  682. self.assertIsInvalid(
  683. ValidationTestModelAdmin, ValidationTestModel,
  684. "The value of 'prepopulated_fields' must be a dictionary.",
  685. 'admin.E026')
  686. def test_missing_field(self):
  687. class ValidationTestModelAdmin(ModelAdmin):
  688. prepopulated_fields = {'non_existent_field': ("slug",)}
  689. self.assertIsInvalid(
  690. ValidationTestModelAdmin, ValidationTestModel,
  691. ("The value of 'prepopulated_fields' refers to 'non_existent_field', "
  692. "which is not an attribute of 'modeladmin.ValidationTestModel'."),
  693. 'admin.E027')
  694. def test_missing_field_again(self):
  695. class ValidationTestModelAdmin(ModelAdmin):
  696. prepopulated_fields = {"slug": ('non_existent_field',)}
  697. self.assertIsInvalid(
  698. ValidationTestModelAdmin, ValidationTestModel,
  699. ("The value of 'prepopulated_fields[\"slug\"][0]' refers to 'non_existent_field', "
  700. "which is not an attribute of 'modeladmin.ValidationTestModel'."),
  701. 'admin.E030')
  702. def test_invalid_field_type(self):
  703. class ValidationTestModelAdmin(ModelAdmin):
  704. prepopulated_fields = {"users": ('name',)}
  705. self.assertIsInvalid(
  706. ValidationTestModelAdmin, ValidationTestModel,
  707. ("The value of 'prepopulated_fields' refers to 'users', which must not be "
  708. "a DateTimeField, ForeignKey or ManyToManyField."),
  709. 'admin.E028')
  710. def test_valid_case(self):
  711. class ValidationTestModelAdmin(ModelAdmin):
  712. prepopulated_fields = {"slug": ('name',)}
  713. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  714. class ListDisplayTests(CheckTestCase):
  715. def test_not_iterable(self):
  716. class ValidationTestModelAdmin(ModelAdmin):
  717. list_display = 10
  718. self.assertIsInvalid(
  719. ValidationTestModelAdmin, ValidationTestModel,
  720. "The value of 'list_display' must be a list or tuple.",
  721. 'admin.E107')
  722. def test_missing_field(self):
  723. class ValidationTestModelAdmin(ModelAdmin):
  724. list_display = ('non_existent_field',)
  725. self.assertIsInvalid(
  726. ValidationTestModelAdmin, ValidationTestModel,
  727. ("The value of 'list_display[0]' refers to 'non_existent_field', which is not a callable, an attribute "
  728. "of 'ValidationTestModelAdmin', or an attribute or method on 'modeladmin.ValidationTestModel'."),
  729. 'admin.E108')
  730. def test_invalid_field_type(self):
  731. class ValidationTestModelAdmin(ModelAdmin):
  732. list_display = ('users',)
  733. self.assertIsInvalid(
  734. ValidationTestModelAdmin, ValidationTestModel,
  735. "The value of 'list_display[0]' must not be a ManyToManyField.",
  736. 'admin.E109')
  737. def test_valid_case(self):
  738. def a_callable(obj):
  739. pass
  740. class ValidationTestModelAdmin(ModelAdmin):
  741. def a_method(self, obj):
  742. pass
  743. list_display = ('name', 'decade_published_in', 'a_method', a_callable)
  744. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  745. class ListDisplayLinksCheckTests(CheckTestCase):
  746. def test_not_iterable(self):
  747. class ValidationTestModelAdmin(ModelAdmin):
  748. list_display_links = 10
  749. self.assertIsInvalid(
  750. ValidationTestModelAdmin, ValidationTestModel,
  751. "The value of 'list_display_links' must be a list, a tuple, or None.",
  752. 'admin.E110')
  753. def test_missing_field(self):
  754. class ValidationTestModelAdmin(ModelAdmin):
  755. list_display_links = ('non_existent_field',)
  756. self.assertIsInvalid(
  757. ValidationTestModelAdmin, ValidationTestModel,
  758. "The value of 'list_display_links[0]' refers to 'non_existent_field', which is not defined in 'list_display'.",
  759. 'admin.E111')
  760. def test_missing_in_list_display(self):
  761. class ValidationTestModelAdmin(ModelAdmin):
  762. list_display_links = ('name',)
  763. self.assertIsInvalid(
  764. ValidationTestModelAdmin, ValidationTestModel,
  765. "The value of 'list_display_links[0]' refers to 'name', which is not defined in 'list_display'.",
  766. 'admin.E111')
  767. def test_valid_case(self):
  768. def a_callable(obj):
  769. pass
  770. class ValidationTestModelAdmin(ModelAdmin):
  771. def a_method(self, obj):
  772. pass
  773. list_display = ('name', 'decade_published_in', 'a_method', a_callable)
  774. list_display_links = ('name', 'decade_published_in', 'a_method', a_callable)
  775. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  776. def test_None_is_valid_case(self):
  777. class ValidationTestModelAdmin(ModelAdmin):
  778. list_display_links = None
  779. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  780. class ListFilterTests(CheckTestCase):
  781. def test_list_filter_validation(self):
  782. class ValidationTestModelAdmin(ModelAdmin):
  783. list_filter = 10
  784. self.assertIsInvalid(
  785. ValidationTestModelAdmin, ValidationTestModel,
  786. "The value of 'list_filter' must be a list or tuple.",
  787. 'admin.E112')
  788. def test_missing_field(self):
  789. class ValidationTestModelAdmin(ModelAdmin):
  790. list_filter = ('non_existent_field',)
  791. self.assertIsInvalid(
  792. ValidationTestModelAdmin, ValidationTestModel,
  793. "The value of 'list_filter[0]' refers to 'non_existent_field', which does not refer to a Field.",
  794. 'admin.E116')
  795. def test_not_filter(self):
  796. class RandomClass(object):
  797. pass
  798. class ValidationTestModelAdmin(ModelAdmin):
  799. list_filter = (RandomClass,)
  800. self.assertIsInvalid(
  801. ValidationTestModelAdmin, ValidationTestModel,
  802. "The value of 'list_filter[0]' must inherit from 'ListFilter'.",
  803. 'admin.E113')
  804. def test_not_filter_again(self):
  805. class RandomClass(object):
  806. pass
  807. class ValidationTestModelAdmin(ModelAdmin):
  808. list_filter = (('is_active', RandomClass),)
  809. self.assertIsInvalid(
  810. ValidationTestModelAdmin, ValidationTestModel,
  811. "The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.",
  812. 'admin.E115')
  813. def test_not_filter_again_again(self):
  814. class AwesomeFilter(SimpleListFilter):
  815. def get_title(self):
  816. return 'awesomeness'
  817. def get_choices(self, request):
  818. return (('bit', 'A bit awesome'), ('very', 'Very awesome'), )
  819. def get_queryset(self, cl, qs):
  820. return qs
  821. class ValidationTestModelAdmin(ModelAdmin):
  822. list_filter = (('is_active', AwesomeFilter),)
  823. self.assertIsInvalid(
  824. ValidationTestModelAdmin, ValidationTestModel,
  825. "The value of 'list_filter[0][1]' must inherit from 'FieldListFilter'.",
  826. 'admin.E115')
  827. def test_not_associated_with_field_name(self):
  828. class ValidationTestModelAdmin(ModelAdmin):
  829. list_filter = (BooleanFieldListFilter,)
  830. self.assertIsInvalid(
  831. ValidationTestModelAdmin, ValidationTestModel,
  832. "The value of 'list_filter[0]' must not inherit from 'FieldListFilter'.",
  833. 'admin.E114')
  834. def test_valid_case(self):
  835. class AwesomeFilter(SimpleListFilter):
  836. def get_title(self):
  837. return 'awesomeness'
  838. def get_choices(self, request):
  839. return (('bit', 'A bit awesome'), ('very', 'Very awesome'), )
  840. def get_queryset(self, cl, qs):
  841. return qs
  842. class ValidationTestModelAdmin(ModelAdmin):
  843. list_filter = ('is_active', AwesomeFilter, ('is_active', BooleanFieldListFilter), 'no')
  844. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  845. class ListPerPageCheckTests(CheckTestCase):
  846. def test_not_integer(self):
  847. class ValidationTestModelAdmin(ModelAdmin):
  848. list_per_page = 'hello'
  849. self.assertIsInvalid(
  850. ValidationTestModelAdmin, ValidationTestModel,
  851. "The value of 'list_per_page' must be an integer.",
  852. 'admin.E118')
  853. def test_valid_case(self):
  854. class ValidationTestModelAdmin(ModelAdmin):
  855. list_per_page = 100
  856. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  857. class ListMaxShowAllCheckTests(CheckTestCase):
  858. def test_not_integer(self):
  859. class ValidationTestModelAdmin(ModelAdmin):
  860. list_max_show_all = 'hello'
  861. self.assertIsInvalid(
  862. ValidationTestModelAdmin, ValidationTestModel,
  863. "The value of 'list_max_show_all' must be an integer.",
  864. 'admin.E119')
  865. def test_valid_case(self):
  866. class ValidationTestModelAdmin(ModelAdmin):
  867. list_max_show_all = 200
  868. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  869. class SearchFieldsCheckTests(CheckTestCase):
  870. def test_not_iterable(self):
  871. class ValidationTestModelAdmin(ModelAdmin):
  872. search_fields = 10
  873. self.assertIsInvalid(
  874. ValidationTestModelAdmin, ValidationTestModel,
  875. "The value of 'search_fields' must be a list or tuple.",
  876. 'admin.E126')
  877. class DateHierarchyCheckTests(CheckTestCase):
  878. def test_missing_field(self):
  879. class ValidationTestModelAdmin(ModelAdmin):
  880. date_hierarchy = 'non_existent_field'
  881. self.assertIsInvalid(
  882. ValidationTestModelAdmin, ValidationTestModel,
  883. ("The value of 'date_hierarchy' refers to 'non_existent_field', which "
  884. "is not an attribute of 'modeladmin.ValidationTestModel'."),
  885. 'admin.E127')
  886. def test_invalid_field_type(self):
  887. class ValidationTestModelAdmin(ModelAdmin):
  888. date_hierarchy = 'name'
  889. self.assertIsInvalid(
  890. ValidationTestModelAdmin, ValidationTestModel,
  891. "The value of 'date_hierarchy' must be a DateField or DateTimeField.",
  892. 'admin.E128')
  893. def test_valid_case(self):
  894. class ValidationTestModelAdmin(ModelAdmin):
  895. date_hierarchy = 'pub_date'
  896. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  897. class OrderingCheckTests(CheckTestCase):
  898. def test_not_iterable(self):
  899. class ValidationTestModelAdmin(ModelAdmin):
  900. ordering = 10
  901. self.assertIsInvalid(
  902. ValidationTestModelAdmin, ValidationTestModel,
  903. "The value of 'ordering' must be a list or tuple.",
  904. 'admin.E031')
  905. class ValidationTestModelAdmin(ModelAdmin):
  906. ordering = ('non_existent_field',)
  907. self.assertIsInvalid(
  908. ValidationTestModelAdmin,
  909. ValidationTestModel,
  910. "The value of 'ordering[0]' refers to 'non_existent_field', which is not an attribute of 'modeladmin.ValidationTestModel'.",
  911. 'admin.E033',
  912. )
  913. def test_random_marker_not_alone(self):
  914. class ValidationTestModelAdmin(ModelAdmin):
  915. ordering = ('?', 'name')
  916. self.assertIsInvalid(
  917. ValidationTestModelAdmin, ValidationTestModel,
  918. ("The value of 'ordering' has the random ordering marker '?', but contains "
  919. "other fields as well."),
  920. 'admin.E032',
  921. hint='Either remove the "?", or remove the other fields.')
  922. def test_valid_random_marker_case(self):
  923. class ValidationTestModelAdmin(ModelAdmin):
  924. ordering = ('?',)
  925. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  926. def test_valid_complex_case(self):
  927. class ValidationTestModelAdmin(ModelAdmin):
  928. ordering = ('band__name',)
  929. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  930. def test_valid_case(self):
  931. class ValidationTestModelAdmin(ModelAdmin):
  932. ordering = ('name',)
  933. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  934. class ListSelectRelatedCheckTests(CheckTestCase):
  935. def test_invalid_type(self):
  936. class ValidationTestModelAdmin(ModelAdmin):
  937. list_select_related = 1
  938. self.assertIsInvalid(ValidationTestModelAdmin, ValidationTestModel,
  939. "The value of 'list_select_related' must be a boolean, tuple or list.",
  940. 'admin.E117')
  941. def test_valid_case(self):
  942. class ValidationTestModelAdmin(ModelAdmin):
  943. list_select_related = False
  944. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  945. class SaveAsCheckTests(CheckTestCase):
  946. def test_not_boolean(self):
  947. class ValidationTestModelAdmin(ModelAdmin):
  948. save_as = 1
  949. self.assertIsInvalid(
  950. ValidationTestModelAdmin, ValidationTestModel,
  951. "The value of 'save_as' must be a boolean.",
  952. 'admin.E101')
  953. def test_valid_case(self):
  954. class ValidationTestModelAdmin(ModelAdmin):
  955. save_as = True
  956. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  957. class SaveOnTopCheckTests(CheckTestCase):
  958. def test_not_boolean(self):
  959. class ValidationTestModelAdmin(ModelAdmin):
  960. save_on_top = 1
  961. self.assertIsInvalid(
  962. ValidationTestModelAdmin, ValidationTestModel,
  963. "The value of 'save_on_top' must be a boolean.",
  964. 'admin.E102')
  965. def test_valid_case(self):
  966. class ValidationTestModelAdmin(ModelAdmin):
  967. save_on_top = True
  968. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  969. class InlinesCheckTests(CheckTestCase):
  970. def test_not_iterable(self):
  971. class ValidationTestModelAdmin(ModelAdmin):
  972. inlines = 10
  973. self.assertIsInvalid(
  974. ValidationTestModelAdmin, ValidationTestModel,
  975. "The value of 'inlines' must be a list or tuple.",
  976. 'admin.E103')
  977. def test_not_model_admin(self):
  978. class ValidationTestInline(object):
  979. pass
  980. class ValidationTestModelAdmin(ModelAdmin):
  981. inlines = [ValidationTestInline]
  982. self.assertIsInvalidRegexp(
  983. ValidationTestModelAdmin, ValidationTestModel,
  984. r"'.*\.ValidationTestInline' must inherit from 'BaseModelAdmin'\.",
  985. 'admin.E104')
  986. def test_missing_model_field(self):
  987. class ValidationTestInline(TabularInline):
  988. pass
  989. class ValidationTestModelAdmin(ModelAdmin):
  990. inlines = [ValidationTestInline]
  991. self.assertIsInvalidRegexp(
  992. ValidationTestModelAdmin, ValidationTestModel,
  993. r"'.*\.ValidationTestInline' must have a 'model' attribute\.",
  994. 'admin.E105')
  995. def test_invalid_model_type(self):
  996. """ Test if `model` attribute on inline model admin is a models.Model.
  997. """
  998. class SomethingBad(object):
  999. pass
  1000. class ValidationTestInline(TabularInline):
  1001. model = SomethingBad
  1002. class ValidationTestModelAdmin(ModelAdmin):
  1003. inlines = [ValidationTestInline]
  1004. self.assertIsInvalidRegexp(
  1005. ValidationTestModelAdmin, ValidationTestModel,
  1006. r"The value of '.*\.ValidationTestInline.model' must be a Model\.",
  1007. 'admin.E106')
  1008. def test_valid_case(self):
  1009. class ValidationTestInline(TabularInline):
  1010. model = ValidationTestInlineModel
  1011. class ValidationTestModelAdmin(ModelAdmin):
  1012. inlines = [ValidationTestInline]
  1013. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  1014. class FkNameCheckTests(CheckTestCase):
  1015. def test_missing_field(self):
  1016. class ValidationTestInline(TabularInline):
  1017. model = ValidationTestInlineModel
  1018. fk_name = 'non_existent_field'
  1019. class ValidationTestModelAdmin(ModelAdmin):
  1020. inlines = [ValidationTestInline]
  1021. self.assertIsInvalid(
  1022. ValidationTestModelAdmin, ValidationTestModel,
  1023. "'modeladmin.ValidationTestInlineModel' has no field named 'non_existent_field'.",
  1024. 'admin.E202',
  1025. invalid_obj=ValidationTestInline)
  1026. def test_valid_case(self):
  1027. class ValidationTestInline(TabularInline):
  1028. model = ValidationTestInlineModel
  1029. fk_name = "parent"
  1030. class ValidationTestModelAdmin(ModelAdmin):
  1031. inlines = [ValidationTestInline]
  1032. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  1033. class ExtraCheckTests(CheckTestCase):
  1034. def test_not_integer(self):
  1035. class ValidationTestInline(TabularInline):
  1036. model = ValidationTestInlineModel
  1037. extra = "hello"
  1038. class ValidationTestModelAdmin(ModelAdmin):
  1039. inlines = [ValidationTestInline]
  1040. self.assertIsInvalid(
  1041. ValidationTestModelAdmin, ValidationTestModel,
  1042. "The value of 'extra' must be an integer.",
  1043. 'admin.E203',
  1044. invalid_obj=ValidationTestInline)
  1045. def test_valid_case(self):
  1046. class ValidationTestInline(TabularInline):
  1047. model = ValidationTestInlineModel
  1048. extra = 2
  1049. class ValidationTestModelAdmin(ModelAdmin):
  1050. inlines = [ValidationTestInline]
  1051. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  1052. class MaxNumCheckTests(CheckTestCase):
  1053. def test_not_integer(self):
  1054. class ValidationTestInline(TabularInline):
  1055. model = ValidationTestInlineModel
  1056. max_num = "hello"
  1057. class ValidationTestModelAdmin(ModelAdmin):
  1058. inlines = [ValidationTestInline]
  1059. self.assertIsInvalid(
  1060. ValidationTestModelAdmin, ValidationTestModel,
  1061. "The value of 'max_num' must be an integer.",
  1062. 'admin.E204',
  1063. invalid_obj=ValidationTestInline)
  1064. def test_valid_case(self):
  1065. class ValidationTestInline(TabularInline):
  1066. model = ValidationTestInlineModel
  1067. max_num = 2
  1068. class ValidationTestModelAdmin(ModelAdmin):
  1069. inlines = [ValidationTestInline]
  1070. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  1071. class MinNumCheckTests(CheckTestCase):
  1072. def test_not_integer(self):
  1073. class ValidationTestInline(TabularInline):
  1074. model = ValidationTestInlineModel
  1075. min_num = "hello"
  1076. class ValidationTestModelAdmin(ModelAdmin):
  1077. inlines = [ValidationTestInline]
  1078. self.assertIsInvalid(
  1079. ValidationTestModelAdmin, ValidationTestModel,
  1080. "The value of 'min_num' must be an integer.",
  1081. 'admin.E205',
  1082. invalid_obj=ValidationTestInline)
  1083. def test_valid_case(self):
  1084. class ValidationTestInline(TabularInline):
  1085. model = ValidationTestInlineModel
  1086. min_num = 2
  1087. class ValidationTestModelAdmin(ModelAdmin):
  1088. inlines = [ValidationTestInline]
  1089. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  1090. class FormsetCheckTests(CheckTestCase):
  1091. def test_invalid_type(self):
  1092. class FakeFormSet(object):
  1093. pass
  1094. class ValidationTestInline(TabularInline):
  1095. model = ValidationTestInlineModel
  1096. formset = FakeFormSet
  1097. class ValidationTestModelAdmin(ModelAdmin):
  1098. inlines = [ValidationTestInline]
  1099. self.assertIsInvalid(
  1100. ValidationTestModelAdmin, ValidationTestModel,
  1101. "The value of 'formset' must inherit from 'BaseModelFormSet'.",
  1102. 'admin.E206',
  1103. invalid_obj=ValidationTestInline)
  1104. def test_valid_case(self):
  1105. class RealModelFormSet(BaseModelFormSet):
  1106. pass
  1107. class ValidationTestInline(TabularInline):
  1108. model = ValidationTestInlineModel
  1109. formset = RealModelFormSet
  1110. class ValidationTestModelAdmin(ModelAdmin):
  1111. inlines = [ValidationTestInline]
  1112. self.assertIsValid(ValidationTestModelAdmin, ValidationTestModel)
  1113. class CustomModelAdminTests(CheckTestCase):
  1114. def test_deprecation(self):
  1115. "Deprecated Custom Validator definitions still work with the check framework."
  1116. with warnings.catch_warnings():
  1117. warnings.simplefilter("ignore", category=RemovedInDjango19Warning)
  1118. class CustomValidator(ModelAdminValidator):
  1119. def validate_me(self, model_admin, model):
  1120. raise ImproperlyConfigured('error!')
  1121. class CustomModelAdmin(ModelAdmin):
  1122. validator_class = CustomValidator
  1123. self.assertIsInvalid(CustomModelAdmin, ValidationTestModel, 'error!')