|
1 | 1 | from datetime import date |
2 | 2 | from typing import Optional |
3 | 3 |
|
| 4 | +import nh3 |
4 | 5 | from django import forms |
5 | 6 | from django.conf import settings |
6 | 7 | from django.contrib.postgres.fields import ArrayField |
@@ -73,10 +74,40 @@ def order_by_end_date(self): |
73 | 74 | return qs.order_by("end_date") |
74 | 75 |
|
75 | 76 |
|
| 77 | +class AsJsonMixin: |
| 78 | + @cached_property |
| 79 | + def as_json(self): |
| 80 | + # Clean the strings in title and description. |
| 81 | + title = nh3.clean(self.title, tags=set()) |
| 82 | + description = nh3.clean(self.description, tags=set()) |
| 83 | + # If image exist scale it down and convert to webp. |
| 84 | + image = ( |
| 85 | + self.image.get_rendition("max-1200x1200|format-webp|webpquality-60").url |
| 86 | + if self.image |
| 87 | + else "" |
| 88 | + ) |
| 89 | + # Make sure weight is an int. |
| 90 | + weight = int(self.weight) |
| 91 | + # If next deadline exist and is set to show, format it as standard iso date. |
| 92 | + try: |
| 93 | + next_deadline = ( |
| 94 | + self.next_deadline().isoformat() if self.show_deadline else "" |
| 95 | + ) |
| 96 | + except AttributeError: |
| 97 | + next_deadline = "" |
| 98 | + return { |
| 99 | + "title": title, |
| 100 | + "description": description, |
| 101 | + "image": image, |
| 102 | + "weight": weight, |
| 103 | + "next_deadline": next_deadline, |
| 104 | + } |
| 105 | + |
| 106 | + |
76 | 107 | @method_decorator( |
77 | 108 | ratelimit(key="ip", rate=settings.DEFAULT_RATE_LIMIT, method="POST"), name="serve" |
78 | 109 | ) |
79 | | -class ApplicationBase(EmailForm, WorkflowStreamForm): # type: ignore |
| 110 | +class ApplicationBase(EmailForm, WorkflowStreamForm, AsJsonMixin): # type: ignore |
80 | 111 | is_creatable = False |
81 | 112 |
|
82 | 113 | # Adds validation around forms & workflows. Isn't on Workflow class due to not displaying workflow field on Round |
@@ -555,7 +586,7 @@ def serve(self, request, *args, **kwargs): |
555 | 586 | @method_decorator( |
556 | 587 | ratelimit(key="ip", rate=settings.DEFAULT_RATE_LIMIT, method="POST"), name="serve" |
557 | 588 | ) |
558 | | -class LabBase(EmailForm, WorkflowStreamForm, SubmittableStreamForm): # type: ignore |
| 589 | +class LabBase(EmailForm, WorkflowStreamForm, SubmittableStreamForm, AsJsonMixin): # type: ignore |
559 | 590 | is_creatable = False |
560 | 591 | submission_class = ApplicationSubmission |
561 | 592 |
|
|
0 commit comments