test_edit.py 18 KB

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