You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. from django.core.exceptions import ImproperlyConfigured
  2. from django.forms import models as model_forms
  3. from django.http import HttpResponseRedirect
  4. from django.views.generic.base import ContextMixin, TemplateResponseMixin, View
  5. from django.views.generic.detail import (
  6. BaseDetailView, SingleObjectMixin, SingleObjectTemplateResponseMixin,
  7. )
  8. class FormMixin(ContextMixin):
  9. """Provide a way to show and handle a form in a request."""
  10. initial = {}
  11. form_class = None
  12. success_url = None
  13. prefix = None
  14. def get_initial(self):
  15. """Return the initial data to use for forms on this view."""
  16. return self.initial.copy()
  17. def get_prefix(self):
  18. """Return the prefix to use for forms."""
  19. return self.prefix
  20. def get_form_class(self):
  21. """Return the form class to use."""
  22. return self.form_class
  23. def get_form(self, form_class=None):
  24. """Return an instance of the form to be used in this view."""
  25. if form_class is None:
  26. form_class = self.get_form_class()
  27. return form_class(**self.get_form_kwargs())
  28. def get_form_kwargs(self):
  29. """Return the keyword arguments for instantiating the form."""
  30. kwargs = {
  31. 'initial': self.get_initial(),
  32. 'prefix': self.get_prefix(),
  33. }
  34. if self.request.method in ('POST', 'PUT'):
  35. kwargs.update({
  36. 'data': self.request.POST,
  37. 'files': self.request.FILES,
  38. })
  39. return kwargs
  40. def get_success_url(self):
  41. """Return the URL to redirect to after processing a valid form."""
  42. if not self.success_url:
  43. raise ImproperlyConfigured("No URL to redirect to. Provide a success_url.")
  44. return str(self.success_url) # success_url may be lazy
  45. def form_valid(self, form):
  46. """If the form is valid, redirect to the supplied URL."""
  47. return HttpResponseRedirect(self.get_success_url())
  48. def form_invalid(self, form):
  49. """If the form is invalid, render the invalid form."""
  50. return self.render_to_response(self.get_context_data(form=form))
  51. def get_context_data(self, **kwargs):
  52. """Insert the form into the context dict."""
  53. if 'form' not in kwargs:
  54. kwargs['form'] = self.get_form()
  55. return super().get_context_data(**kwargs)
  56. class ModelFormMixin(FormMixin, SingleObjectMixin):
  57. """Provide a way to show and handle a ModelForm in a request."""
  58. fields = None
  59. def get_form_class(self):
  60. """Return the form class to use in this view."""
  61. if self.fields is not None and self.form_class:
  62. raise ImproperlyConfigured(
  63. "Specifying both 'fields' and 'form_class' is not permitted."
  64. )
  65. if self.form_class:
  66. return self.form_class
  67. else:
  68. if self.model is not None:
  69. # If a model has been explicitly provided, use it
  70. model = self.model
  71. elif getattr(self, 'object', None) is not None:
  72. # If this view is operating on a single object, use
  73. # the class of that object
  74. model = self.object.__class__
  75. else:
  76. # Try to get a queryset and extract the model class
  77. # from that
  78. model = self.get_queryset().model
  79. if self.fields is None:
  80. raise ImproperlyConfigured(
  81. "Using ModelFormMixin (base class of %s) without "
  82. "the 'fields' attribute is prohibited." % self.__class__.__name__
  83. )
  84. return model_forms.modelform_factory(model, fields=self.fields)
  85. def get_form_kwargs(self):
  86. """Return the keyword arguments for instantiating the form."""
  87. kwargs = super().get_form_kwargs()
  88. if hasattr(self, 'object'):
  89. kwargs.update({'instance': self.object})
  90. return kwargs
  91. def get_success_url(self):
  92. """Return the URL to redirect to after processing a valid form."""
  93. if self.success_url:
  94. url = self.success_url.format(**self.object.__dict__)
  95. else:
  96. try:
  97. url = self.object.get_absolute_url()
  98. except AttributeError:
  99. raise ImproperlyConfigured(
  100. "No URL to redirect to. Either provide a url or define"
  101. " a get_absolute_url method on the Model.")
  102. return url
  103. def form_valid(self, form):
  104. """If the form is valid, save the associated model."""
  105. self.object = form.save()
  106. return super().form_valid(form)
  107. class ProcessFormView(View):
  108. """Render a form on GET and processes it on POST."""
  109. def get(self, request, *args, **kwargs):
  110. """Handle GET requests: instantiate a blank version of the form."""
  111. return self.render_to_response(self.get_context_data())
  112. def post(self, request, *args, **kwargs):
  113. """
  114. Handle POST requests: instantiate a form instance with the passed
  115. POST variables and then check if it's valid.
  116. """
  117. form = self.get_form()
  118. if form.is_valid():
  119. return self.form_valid(form)
  120. else:
  121. return self.form_invalid(form)
  122. # PUT is a valid HTTP verb for creating (with a known URL) or editing an
  123. # object, note that browsers only support POST for now.
  124. def put(self, *args, **kwargs):
  125. return self.post(*args, **kwargs)
  126. class BaseFormView(FormMixin, ProcessFormView):
  127. """A base view for displaying a form."""
  128. class FormView(TemplateResponseMixin, BaseFormView):
  129. """A view for displaying a form and rendering a template response."""
  130. class BaseCreateView(ModelFormMixin, ProcessFormView):
  131. """
  132. Base view for creating a new object instance.
  133. Using this base class requires subclassing to provide a response mixin.
  134. """
  135. def get(self, request, *args, **kwargs):
  136. self.object = None
  137. return super().get(request, *args, **kwargs)
  138. def post(self, request, *args, **kwargs):
  139. self.object = None
  140. return super().post(request, *args, **kwargs)
  141. class CreateView(SingleObjectTemplateResponseMixin, BaseCreateView):
  142. """
  143. View for creating a new object, with a response rendered by a template.
  144. """
  145. template_name_suffix = '_form'
  146. class BaseUpdateView(ModelFormMixin, ProcessFormView):
  147. """
  148. Base view for updating an existing object.
  149. Using this base class requires subclassing to provide a response mixin.
  150. """
  151. def get(self, request, *args, **kwargs):
  152. self.object = self.get_object()
  153. return super().get(request, *args, **kwargs)
  154. def post(self, request, *args, **kwargs):
  155. self.object = self.get_object()
  156. return super().post(request, *args, **kwargs)
  157. class UpdateView(SingleObjectTemplateResponseMixin, BaseUpdateView):
  158. """View for updating an object, with a response rendered by a template."""
  159. template_name_suffix = '_form'
  160. class DeletionMixin:
  161. """Provide the ability to delete objects."""
  162. success_url = None
  163. def delete(self, request, *args, **kwargs):
  164. """
  165. Call the delete() method on the fetched object and then redirect to the
  166. success URL.
  167. """
  168. self.object = self.get_object()
  169. success_url = self.get_success_url()
  170. self.object.delete()
  171. return HttpResponseRedirect(success_url)
  172. # Add support for browsers which only accept GET and POST for now.
  173. def post(self, request, *args, **kwargs):
  174. return self.delete(request, *args, **kwargs)
  175. def get_success_url(self):
  176. if self.success_url:
  177. return self.success_url.format(**self.object.__dict__)
  178. else:
  179. raise ImproperlyConfigured(
  180. "No URL to redirect to. Provide a success_url.")
  181. class BaseDeleteView(DeletionMixin, BaseDetailView):
  182. """
  183. Base view for deleting an object.
  184. Using this base class requires subclassing to provide a response mixin.
  185. """
  186. class DeleteView(SingleObjectTemplateResponseMixin, BaseDeleteView):
  187. """
  188. View for deleting an object retrieved with self.get_object(), with a
  189. response rendered by a template.
  190. """
  191. template_name_suffix = '_confirm_delete'