Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

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