test_edit.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. from __future__ import unicode_literals
  2. import warnings
  3. from django import forms
  4. from django.core.exceptions import ImproperlyConfigured
  5. from django.core.urlresolvers import reverse
  6. from django.test import TestCase, ignore_warnings, override_settings
  7. from django.test.client import RequestFactory
  8. from django.utils.deprecation import RemovedInDjango20Warning
  9. from django.views.generic.base import View
  10. from django.views.generic.edit import CreateView, FormMixin, ModelFormMixin
  11. from . import views
  12. from .models import Artist, Author
  13. from .test_forms import AuthorForm
  14. class FormMixinTests(TestCase):
  15. def test_initial_data(self):
  16. """ Test instance independence of initial data dict (see #16138) """
  17. initial_1 = FormMixin().get_initial()
  18. initial_1['foo'] = 'bar'
  19. initial_2 = FormMixin().get_initial()
  20. self.assertNotEqual(initial_1, initial_2)
  21. def test_get_prefix(self):
  22. """ Test prefix can be set (see #18872) """
  23. test_string = 'test'
  24. rf = RequestFactory()
  25. get_request = rf.get('/')
  26. class TestFormMixin(FormMixin):
  27. request = get_request
  28. default_kwargs = TestFormMixin().get_form_kwargs()
  29. self.assertEqual(None, default_kwargs.get('prefix'))
  30. set_mixin = TestFormMixin()
  31. set_mixin.prefix = test_string
  32. set_kwargs = set_mixin.get_form_kwargs()
  33. self.assertEqual(test_string, set_kwargs.get('prefix'))
  34. def test_get_form(self):
  35. class TestFormMixin(FormMixin):
  36. request = RequestFactory().get('/')
  37. self.assertIsInstance(
  38. TestFormMixin().get_form(forms.Form), forms.Form,
  39. 'get_form() should use provided form class.'
  40. )
  41. class FormClassTestFormMixin(TestFormMixin):
  42. form_class = forms.Form
  43. self.assertIsInstance(
  44. FormClassTestFormMixin().get_form(), forms.Form,
  45. 'get_form() should fallback to get_form_class() if none is provided.'
  46. )
  47. def test_get_form_missing_form_class_default_value(self):
  48. with warnings.catch_warnings(record=True) as w:
  49. warnings.filterwarnings('always')
  50. class MissingDefaultValue(FormMixin):
  51. request = RequestFactory().get('/')
  52. form_class = forms.Form
  53. def get_form(self, form_class):
  54. return form_class(**self.get_form_kwargs())
  55. self.assertEqual(len(w), 1)
  56. self.assertEqual(w[0].category, RemovedInDjango20Warning)
  57. self.assertEqual(
  58. str(w[0].message),
  59. '`generic_views.test_edit.MissingDefaultValue.get_form` method '
  60. 'must define a default value for its `form_class` argument.'
  61. )
  62. self.assertIsInstance(
  63. MissingDefaultValue().get_form(), forms.Form,
  64. )
  65. def test_get_context_data(self):
  66. class FormContext(FormMixin):
  67. request = RequestFactory().get('/')
  68. form_class = forms.Form
  69. self.assertIsInstance(FormContext().get_context_data()['form'], forms.Form)
  70. @override_settings(ROOT_URLCONF='generic_views.urls')
  71. class BasicFormTests(TestCase):
  72. def test_post_data(self):
  73. res = self.client.post('/contact/', {'name': "Me", 'message': "Hello"})
  74. self.assertRedirects(res, '/list/authors/')
  75. class ModelFormMixinTests(TestCase):
  76. def test_get_form(self):
  77. form_class = views.AuthorGetQuerySetFormView().get_form_class()
  78. self.assertEqual(form_class._meta.model, Author)
  79. def test_get_form_checks_for_object(self):
  80. mixin = ModelFormMixin()
  81. mixin.request = RequestFactory().get('/')
  82. self.assertEqual({'initial': {}, 'prefix': None},
  83. mixin.get_form_kwargs())
  84. @override_settings(ROOT_URLCONF='generic_views.urls')
  85. class CreateViewTests(TestCase):
  86. def test_create(self):
  87. res = self.client.get('/edit/authors/create/')
  88. self.assertEqual(res.status_code, 200)
  89. self.assertIsInstance(res.context['form'], forms.ModelForm)
  90. self.assertIsInstance(res.context['view'], View)
  91. self.assertNotIn('object', res.context)
  92. self.assertNotIn('author', res.context)
  93. self.assertTemplateUsed(res, 'generic_views/author_form.html')
  94. res = self.client.post('/edit/authors/create/',
  95. {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  96. self.assertEqual(res.status_code, 302)
  97. self.assertRedirects(res, '/list/authors/')
  98. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
  99. def test_create_invalid(self):
  100. res = self.client.post('/edit/authors/create/',
  101. {'name': 'A' * 101, 'slug': 'randall-munroe'})
  102. self.assertEqual(res.status_code, 200)
  103. self.assertTemplateUsed(res, 'generic_views/author_form.html')
  104. self.assertEqual(len(res.context['form'].errors), 1)
  105. self.assertEqual(Author.objects.count(), 0)
  106. def test_create_with_object_url(self):
  107. res = self.client.post('/edit/artists/create/',
  108. {'name': 'Rene Magritte'})
  109. self.assertEqual(res.status_code, 302)
  110. artist = Artist.objects.get(name='Rene Magritte')
  111. self.assertRedirects(res, '/detail/artist/%d/' % artist.pk)
  112. self.assertQuerysetEqual(Artist.objects.all(), ['<Artist: Rene Magritte>'])
  113. def test_create_with_redirect(self):
  114. res = self.client.post('/edit/authors/create/redirect/',
  115. {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  116. self.assertEqual(res.status_code, 302)
  117. self.assertRedirects(res, '/edit/authors/create/')
  118. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
  119. @ignore_warnings(category=RemovedInDjango20Warning)
  120. def test_create_with_interpolated_redirect(self):
  121. res = self.client.post(
  122. '/edit/authors/create/interpolate_redirect/',
  123. {'name': 'Randall Munroe', 'slug': 'randall-munroe'}
  124. )
  125. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
  126. self.assertEqual(res.status_code, 302)
  127. pk = Author.objects.first().pk
  128. self.assertRedirects(res, '/edit/author/%d/update/' % pk)
  129. # Also test with escaped chars in URL
  130. res = self.client.post(
  131. '/edit/authors/create/interpolate_redirect_nonascii/',
  132. {'name': 'John Doe', 'slug': 'john-doe'}
  133. )
  134. self.assertEqual(res.status_code, 302)
  135. pk = Author.objects.get(name='John Doe').pk
  136. self.assertRedirects(res, '/%C3%A9dit/author/{}/update/'.format(pk))
  137. def test_create_with_special_properties(self):
  138. res = self.client.get('/edit/authors/create/special/')
  139. self.assertEqual(res.status_code, 200)
  140. self.assertIsInstance(res.context['form'], views.AuthorForm)
  141. self.assertNotIn('object', res.context)
  142. self.assertNotIn('author', res.context)
  143. self.assertTemplateUsed(res, 'generic_views/form.html')
  144. res = self.client.post('/edit/authors/create/special/',
  145. {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  146. self.assertEqual(res.status_code, 302)
  147. obj = Author.objects.get(slug='randall-munroe')
  148. self.assertRedirects(res, reverse('author_detail', kwargs={'pk': obj.pk}))
  149. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
  150. def test_create_without_redirect(self):
  151. try:
  152. self.client.post('/edit/authors/create/naive/',
  153. {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  154. self.fail('Should raise exception -- No redirect URL provided, and no get_absolute_url provided')
  155. except ImproperlyConfigured:
  156. pass
  157. def test_create_restricted(self):
  158. res = self.client.post('/edit/authors/create/restricted/',
  159. {'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  160. self.assertEqual(res.status_code, 302)
  161. self.assertRedirects(res, '/accounts/login/?next=/edit/authors/create/restricted/')
  162. def test_create_view_with_restricted_fields(self):
  163. class MyCreateView(CreateView):
  164. model = Author
  165. fields = ['name']
  166. self.assertEqual(list(MyCreateView().get_form_class().base_fields),
  167. ['name'])
  168. def test_create_view_all_fields(self):
  169. class MyCreateView(CreateView):
  170. model = Author
  171. fields = '__all__'
  172. self.assertEqual(list(MyCreateView().get_form_class().base_fields),
  173. ['name', 'slug'])
  174. def test_create_view_without_explicit_fields(self):
  175. class MyCreateView(CreateView):
  176. model = Author
  177. message = (
  178. "Using ModelFormMixin (base class of MyCreateView) without the "
  179. "'fields' attribute is prohibited."
  180. )
  181. with self.assertRaisesMessage(ImproperlyConfigured, message):
  182. MyCreateView().get_form_class()
  183. def test_define_both_fields_and_form_class(self):
  184. class MyCreateView(CreateView):
  185. model = Author
  186. form_class = AuthorForm
  187. fields = ['name']
  188. message = "Specifying both 'fields' and 'form_class' is not permitted."
  189. with self.assertRaisesMessage(ImproperlyConfigured, message):
  190. MyCreateView().get_form_class()
  191. @override_settings(ROOT_URLCONF='generic_views.urls')
  192. class UpdateViewTests(TestCase):
  193. def test_update_post(self):
  194. a = Author.objects.create(
  195. name='Randall Munroe',
  196. slug='randall-munroe',
  197. )
  198. res = self.client.get('/edit/author/%d/update/' % a.pk)
  199. self.assertEqual(res.status_code, 200)
  200. self.assertIsInstance(res.context['form'], forms.ModelForm)
  201. self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
  202. self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk))
  203. self.assertTemplateUsed(res, 'generic_views/author_form.html')
  204. # Modification with both POST and PUT (browser compatible)
  205. res = self.client.post('/edit/author/%d/update/' % a.pk,
  206. {'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'})
  207. self.assertEqual(res.status_code, 302)
  208. self.assertRedirects(res, '/list/authors/')
  209. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (xkcd)>'])
  210. def test_update_invalid(self):
  211. a = Author.objects.create(
  212. name='Randall Munroe',
  213. slug='randall-munroe',
  214. )
  215. res = self.client.post('/edit/author/%d/update/' % a.pk,
  216. {'name': 'A' * 101, 'slug': 'randall-munroe'})
  217. self.assertEqual(res.status_code, 200)
  218. self.assertTemplateUsed(res, 'generic_views/author_form.html')
  219. self.assertEqual(len(res.context['form'].errors), 1)
  220. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
  221. def test_update_with_object_url(self):
  222. a = Artist.objects.create(name='Rene Magritte')
  223. res = self.client.post('/edit/artists/%d/update/' % a.pk,
  224. {'name': 'Rene Magritte'})
  225. self.assertEqual(res.status_code, 302)
  226. self.assertRedirects(res, '/detail/artist/%d/' % a.pk)
  227. self.assertQuerysetEqual(Artist.objects.all(), ['<Artist: Rene Magritte>'])
  228. def test_update_with_redirect(self):
  229. a = Author.objects.create(
  230. name='Randall Munroe',
  231. slug='randall-munroe',
  232. )
  233. res = self.client.post('/edit/author/%d/update/redirect/' % a.pk,
  234. {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'})
  235. self.assertEqual(res.status_code, 302)
  236. self.assertRedirects(res, '/edit/authors/create/')
  237. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>'])
  238. @ignore_warnings(category=RemovedInDjango20Warning)
  239. def test_update_with_interpolated_redirect(self):
  240. a = Author.objects.create(
  241. name='Randall Munroe',
  242. slug='randall-munroe',
  243. )
  244. res = self.client.post(
  245. '/edit/author/%d/update/interpolate_redirect/' % a.pk,
  246. {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}
  247. )
  248. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>'])
  249. self.assertEqual(res.status_code, 302)
  250. pk = Author.objects.first().pk
  251. self.assertRedirects(res, '/edit/author/%d/update/' % pk)
  252. # Also test with escaped chars in URL
  253. res = self.client.post(
  254. '/edit/author/%d/update/interpolate_redirect_nonascii/' % a.pk,
  255. {'name': 'John Doe', 'slug': 'john-doe'}
  256. )
  257. self.assertEqual(res.status_code, 302)
  258. pk = Author.objects.get(name='John Doe').pk
  259. self.assertRedirects(res, '/%C3%A9dit/author/{}/update/'.format(pk))
  260. def test_update_with_special_properties(self):
  261. a = Author.objects.create(
  262. name='Randall Munroe',
  263. slug='randall-munroe',
  264. )
  265. res = self.client.get('/edit/author/%d/update/special/' % a.pk)
  266. self.assertEqual(res.status_code, 200)
  267. self.assertIsInstance(res.context['form'], views.AuthorForm)
  268. self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
  269. self.assertEqual(res.context['thingy'], Author.objects.get(pk=a.pk))
  270. self.assertNotIn('author', res.context)
  271. self.assertTemplateUsed(res, 'generic_views/form.html')
  272. res = self.client.post('/edit/author/%d/update/special/' % a.pk,
  273. {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'})
  274. self.assertEqual(res.status_code, 302)
  275. self.assertRedirects(res, '/detail/author/%d/' % a.pk)
  276. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>'])
  277. def test_update_without_redirect(self):
  278. a = Author.objects.create(
  279. name='Randall Munroe',
  280. slug='randall-munroe',
  281. )
  282. # Should raise exception -- No redirect URL provided, and no
  283. # get_absolute_url provided
  284. with self.assertRaises(ImproperlyConfigured):
  285. self.client.post('/edit/author/%d/update/naive/' % a.pk,
  286. {'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'})
  287. def test_update_get_object(self):
  288. a = Author.objects.create(
  289. pk=1,
  290. name='Randall Munroe',
  291. slug='randall-munroe',
  292. )
  293. res = self.client.get('/edit/author/update/')
  294. self.assertEqual(res.status_code, 200)
  295. self.assertIsInstance(res.context['form'], forms.ModelForm)
  296. self.assertIsInstance(res.context['view'], View)
  297. self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
  298. self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk))
  299. self.assertTemplateUsed(res, 'generic_views/author_form.html')
  300. # Modification with both POST and PUT (browser compatible)
  301. res = self.client.post('/edit/author/update/',
  302. {'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'})
  303. self.assertEqual(res.status_code, 302)
  304. self.assertRedirects(res, '/list/authors/')
  305. self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (xkcd)>'])
  306. @override_settings(ROOT_URLCONF='generic_views.urls')
  307. class DeleteViewTests(TestCase):
  308. def test_delete_by_post(self):
  309. a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  310. res = self.client.get('/edit/author/%d/delete/' % a.pk)
  311. self.assertEqual(res.status_code, 200)
  312. self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
  313. self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk))
  314. self.assertTemplateUsed(res, 'generic_views/author_confirm_delete.html')
  315. # Deletion with POST
  316. res = self.client.post('/edit/author/%d/delete/' % a.pk)
  317. self.assertEqual(res.status_code, 302)
  318. self.assertRedirects(res, '/list/authors/')
  319. self.assertQuerysetEqual(Author.objects.all(), [])
  320. def test_delete_by_delete(self):
  321. # Deletion with browser compatible DELETE method
  322. a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  323. res = self.client.delete('/edit/author/%d/delete/' % a.pk)
  324. self.assertEqual(res.status_code, 302)
  325. self.assertRedirects(res, '/list/authors/')
  326. self.assertQuerysetEqual(Author.objects.all(), [])
  327. def test_delete_with_redirect(self):
  328. a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  329. res = self.client.post('/edit/author/%d/delete/redirect/' % a.pk)
  330. self.assertEqual(res.status_code, 302)
  331. self.assertRedirects(res, '/edit/authors/create/')
  332. self.assertQuerysetEqual(Author.objects.all(), [])
  333. @ignore_warnings(category=RemovedInDjango20Warning)
  334. def test_delete_with_interpolated_redirect(self):
  335. a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  336. res = self.client.post('/edit/author/%d/delete/interpolate_redirect/' % a.pk)
  337. self.assertEqual(res.status_code, 302)
  338. self.assertRedirects(res, '/edit/authors/create/?deleted=%d' % a.pk)
  339. self.assertQuerysetEqual(Author.objects.all(), [])
  340. # Also test with escaped chars in URL
  341. a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  342. res = self.client.post('/edit/author/{}/delete/interpolate_redirect_nonascii/'.format(a.pk))
  343. self.assertEqual(res.status_code, 302)
  344. self.assertRedirects(res, '/%C3%A9dit/authors/create/?deleted={}'.format(a.pk))
  345. def test_delete_with_special_properties(self):
  346. a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
  347. res = self.client.get('/edit/author/%d/delete/special/' % a.pk)
  348. self.assertEqual(res.status_code, 200)
  349. self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
  350. self.assertEqual(res.context['thingy'], Author.objects.get(pk=a.pk))
  351. self.assertNotIn('author', res.context)
  352. self.assertTemplateUsed(res, 'generic_views/confirm_delete.html')
  353. res = self.client.post('/edit/author/%d/delete/special/' % a.pk)
  354. self.assertEqual(res.status_code, 302)
  355. self.assertRedirects(res, '/list/authors/')
  356. self.assertQuerysetEqual(Author.objects.all(), [])
  357. def test_delete_without_redirect(self):
  358. a = Author.objects.create(
  359. name='Randall Munroe',
  360. slug='randall-munroe',
  361. )
  362. # Should raise exception -- No redirect URL provided, and no
  363. # get_absolute_url provided
  364. with self.assertRaises(ImproperlyConfigured):
  365. self.client.post('/edit/author/%d/delete/naive/' % a.pk)