1from abc import ABC, abstractmethod
2from functools import cached_property
3from typing import Any, NoReturn
4
5from plain.exceptions import ImproperlyConfigured
6from plain.forms import BaseForm, Form
7from plain.http import (
8 NotFoundError404,
9 RedirectResponse,
10 Response,
11 status_for_exception,
12)
13from plain.logs import get_framework_logger
14from plain.paginator import Page, Paginator
15from plain.runtime import settings
16from plain.views import View
17
18from .core import Template, TemplateFileMissing
19
20logger = get_framework_logger("plain.templates")
21
22try:
23 from plain.postgres.exceptions import ObjectDoesNotExist
24except ImportError:
25 ObjectDoesNotExist = None
26
27
28class TemplateView(View):
29 """
30 Render a template.
31 """
32
33 template_name: str | None = None
34
35 def get_template_context(self) -> dict[str, Any]:
36 return {
37 "request": self.request,
38 "template_names": self.get_template_names(),
39 "DEBUG": settings.DEBUG,
40 }
41
42 def get_template_names(self) -> list[str]:
43 """
44 Return a list of template names to be used for the request.
45 """
46 if self.template_name:
47 return [self.template_name]
48
49 return []
50
51 def get_template(self) -> Template:
52 template_names = self.get_template_names()
53
54 if isinstance(template_names, str):
55 raise ImproperlyConfigured(
56 f"{self.__class__.__name__}.get_template_names() must return a list of strings, "
57 f"not a string. Did you mean to return ['{template_names}']?"
58 )
59
60 if not template_names:
61 raise ImproperlyConfigured(
62 f"{self.__class__.__name__} requires a template_name or get_template_names()."
63 )
64
65 for template_name in template_names:
66 try:
67 return Template(template_name)
68 except TemplateFileMissing:
69 pass
70
71 raise TemplateFileMissing(template_names)
72
73 def render(self, *, status_code: int = 200, **context: Any) -> Response:
74 """Render the template to a `Response`, layering `context` over `get_template_context()`.
75
76 A handler passes what the template needs straight in —
77 `self.render(form=form)` — rather than stashing it on `self` for
78 `get_template_context()` to read back. Called with no arguments it
79 renders `get_template_context()` as-is, which is what `get()` does.
80
81 `status_code` sets the response status (a form's 422, say) —
82 `Response.status_code` is fixed at construction, so this is the
83 way to render a template at a non-200 status. The name is
84 reserved: a template variable called `status_code` has to come
85 from `get_template_context()` instead.
86 """
87 return Response(
88 self.get_template().render({**self.get_template_context(), **context}),
89 status_code=status_code,
90 )
91
92 def get(self) -> Response:
93 return self.render()
94
95 def handle_exception(self, exc: Exception) -> Response:
96 """Render `{status}.html` for the exception, falling through on missing template."""
97 status = status_for_exception(exc)
98 try:
99 body = Template(f"{status}.html").render(
100 {
101 "request": self.request,
102 "status_code": status,
103 "exception": exc,
104 "DEBUG": settings.DEBUG,
105 }
106 )
107 return Response(body, status_code=status)
108 except TemplateFileMissing:
109 # Defer to the framework default for plain-text rendering.
110 # `from None` keeps observability tools from seeing
111 # `TemplateFileMissing` as the suppressed cause of `exc`.
112 raise exc from None
113 except Exception as render_exc:
114 if settings.DEBUG:
115 raise
116 logger.error(
117 "Error template render failed",
118 extra={
119 "path": self.request.path,
120 "status_code": status,
121 "request": self.request,
122 },
123 exc_info=render_exc,
124 )
125 return Response(status_code=status)
126
127
128class NotFoundView(TemplateView):
129 """Catchall view: raises 404 before method dispatch, renders `404.html`."""
130
131 def before_request(self) -> NoReturn:
132 raise NotFoundError404
133
134
135class FormView[F: "BaseForm"](TemplateView):
136 """A view for displaying a form and rendering a template response.
137
138 Generic over the form type. Subclasses that want type-safe access to
139 their specific form should parameterize: `FormView[MyForm]`. The
140 `form_class` attribute must still be set separately at runtime.
141 """
142
143 form_class: type[F] | None = None
144 success_url: str | None = None
145
146 def get_form(self) -> F:
147 """Return an instance of the form to be used in this view."""
148 if not self.form_class:
149 raise ImproperlyConfigured(
150 f"No form class provided. Define {self.__class__.__name__}.form_class or override "
151 f"{self.__class__.__name__}.get_form()."
152 )
153 return self.form_class(**self.get_form_kwargs())
154
155 def get_form_kwargs(self) -> dict[str, Any]:
156 """Return the keyword arguments for instantiating the form."""
157 return {
158 "initial": {},
159 "request": self.request,
160 }
161
162 def get_success_url(self, form: F) -> str:
163 """Return the URL to redirect to after processing a valid form."""
164 if not self.success_url:
165 raise ImproperlyConfigured("No URL to redirect to. Provide a success_url.")
166 return str(self.success_url) # success_url may be lazy
167
168 def form_valid(self, form: F) -> Response:
169 """If the form is valid, redirect to the supplied URL."""
170 return RedirectResponse(self.get_success_url(form), status_code=302)
171
172 def get_template_context(self) -> dict[str, Any]:
173 """Insert the form into the context dict."""
174 context = super().get_template_context()
175 context["form"] = self.get_form()
176 return context
177
178 def post(self) -> Response:
179 """Hand a valid form to `form_valid`; re-render an invalid one."""
180 form = self.get_form()
181 if form.is_valid():
182 return self.form_valid(form)
183 return self.render(form=form)
184
185
186class CreateView(FormView):
187 """
188 View for creating a new object, with a response rendered by a template.
189 """
190
191 def get_success_url(self, form: BaseForm) -> str:
192 """Return the URL to redirect to after processing a valid form."""
193 if self.success_url:
194 url = str(self.success_url).format(**self.object.__dict__)
195 else:
196 try:
197 url = self.object.get_absolute_url()
198 except AttributeError:
199 raise ImproperlyConfigured(
200 "No URL to redirect to. Either provide a url or define"
201 " a get_absolute_url method on the Model."
202 )
203 return url
204
205 def form_valid(self, form: BaseForm) -> Response:
206 """If the form is valid, create the associated model."""
207 self.object = form.create() # ty: ignore[unresolved-attribute]
208 return super().form_valid(form)
209
210
211class DetailView(TemplateView, ABC):
212 """
213 Render a "detail" view of an object.
214
215 By default this is a model instance looked up from `self.queryset`, but the
216 view will support display of *any* object by overriding `self.get_object()`.
217 """
218
219 context_object_name = ""
220
221 @cached_property
222 def object(self) -> Any:
223 try:
224 obj = self.get_object()
225 except Exception as e:
226 # If ObjectDoesNotExist is available and this is that exception, raise 404
227 if ObjectDoesNotExist and isinstance(e, ObjectDoesNotExist):
228 raise NotFoundError404
229 # Otherwise, let other exceptions bubble up
230 raise
231
232 # Also raise 404 if get_object() returns None
233 if not obj:
234 raise NotFoundError404
235
236 return obj
237
238 @abstractmethod
239 def get_object(self) -> Any: ...
240
241 def get_template_context(self) -> dict[str, Any]:
242 """Insert the single object into the context dict."""
243 context = super().get_template_context()
244 context["object"] = (
245 self.object
246 ) # Some templates can benefit by always knowing a primary "object" can be present
247 if self.context_object_name:
248 context[self.context_object_name] = self.object
249 return context
250
251
252class UpdateView(DetailView, FormView):
253 """View for updating an object, with a response rendered by a template."""
254
255 def get_success_url(self, form: BaseForm) -> str:
256 """Return the URL to redirect to after processing a valid form."""
257 if self.success_url:
258 url = str(self.success_url).format(**self.object.__dict__)
259 else:
260 try:
261 url = self.object.get_absolute_url()
262 except AttributeError:
263 raise ImproperlyConfigured(
264 "No URL to redirect to. Either provide a url or define"
265 " a get_absolute_url method on the Model."
266 )
267 return url
268
269 def form_valid(self, form: BaseForm) -> Response:
270 """If the form is valid, update the associated model."""
271 self.object = form.update() # ty: ignore[unresolved-attribute]
272 return super().form_valid(form)
273
274 def get_form_kwargs(self) -> dict[str, Any]:
275 """Return the keyword arguments for instantiating the form."""
276 kwargs = super().get_form_kwargs()
277 kwargs.update({"instance": self.object})
278 return kwargs
279
280
281class DeleteView(DetailView, FormView):
282 """
283 View for deleting an object retrieved with self.get_object(), with a
284 response rendered by a template.
285 """
286
287 # An empty confirmation form -- deletion is the view's job, not the
288 # form's, so it carries no fields and no model write.
289 class EmptyDeleteForm(Form):
290 pass
291
292 form_class = EmptyDeleteForm
293
294 def form_valid(self, form: BaseForm) -> Response:
295 """If the confirmation form is valid, delete the object."""
296 self.object.delete()
297 return super().form_valid(form)
298
299
300class ListView(TemplateView, ABC):
301 """
302 Render some list of objects, set by `self.get_objects()`, with a response
303 rendered by a template.
304
305 Set `page_size` to paginate: the objects are wrapped in a `Paginator`, the
306 page number is read from the `?page` query param (invalid values fall back
307 to the first or last page), and the current `Page` is what lands in the
308 template context — iterate it exactly like the full list. The page is also
309 available as `page_obj` for rendering pagination controls; it is `None`
310 when pagination is off. Override `get_page_size()` to compute the size per
311 request.
312
313 A paginated queryset needs a deterministic order (an `order_by()` or a
314 model default) — unordered results can shift between pages. An empty
315 `Page` is falsy, so check `page_obj is not none` to test whether
316 pagination is on.
317 """
318
319 context_object_name = ""
320 page_size: int | None = None
321
322 @cached_property
323 def objects(self) -> Any:
324 return self.get_objects()
325
326 @abstractmethod
327 def get_objects(self) -> Any: ...
328
329 def get_page_size(self) -> int | None:
330 """Page size for pagination, or `None` to render the full list."""
331 return self.page_size
332
333 @cached_property
334 def page_obj(self) -> Page | None:
335 if (page_size := self.get_page_size()) is None:
336 return None
337 return Paginator(self.objects, page_size).get_page(
338 self.request.query_params.get("page", 1)
339 )
340
341 def get_template_context(self) -> dict[str, Any]:
342 """Insert the list of objects (or the current page of it) into the context dict."""
343 context = super().get_template_context()
344 page_obj = self.page_obj
345 objects = page_obj if page_obj is not None else self.objects
346 context["objects"] = objects
347 context["page_obj"] = page_obj
348 if self.context_object_name:
349 context[self.context_object_name] = objects
350 return context
351
352
353__all__ = [
354 "CreateView",
355 "DeleteView",
356 "DetailView",
357 "FormView",
358 "ListView",
359 "NotFoundView",
360 "TemplateView",
361 "UpdateView",
362]