aboutsummaryrefslogtreecommitdiffstats
path: root/pyblackbird_cc/resources/forms.py
blob: 5327def097cd33af40b58aef082eb39187efe5f9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import logging

import magic
from crispy_forms.bootstrap import FormActions
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Button
from crispy_forms.layout import Field
from crispy_forms.layout import Layout
from crispy_forms.layout import Submit
from django import forms

from pyblackbird_cc.resources.models import Resource
from pyblackbird_cc.resources.models import ResourceCategory
from pyblackbird_cc.resources.models import ResourceSubcategory
from pyblackbird_cc.resources.models import ResourceType

from .models import AGE_RANGE_CHOICES
from .models import CURRICULUM_CHOICES

logger = logging.getLogger(__name__)

ALLOWED_THUMBNAILS = 5
ALLOWED_PDFS = 20


def _create_choices_tuple() -> list[tuple[str, str]]:
    """Returns a list of tuples containing resource subcategory names."""
    return sorted(list(ResourceSubcategory.objects.values_list("name", flat=True)), key=str)


class ResourceCreateForm(forms.Form):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.add_input(Submit("submit", "Submit"))
        self.fields["subcategories"].choices = _create_choices_tuple()

    error_css_class = "error"
    required_css_class = "required"

    name = forms.CharField(
        max_length=255,
        help_text="Concisely describe what the resource is, aiming for"
        " in 35-45 characters. "
        "eg: 'Fractions KS2 Worksheet and Answers.'",
    )
    description = forms.CharField(
        max_length=5000,
        widget=forms.Textarea,
        help_text=" You can (and should) use <strong>Markdown</strong> here. "
        "This is your opportunity to clearly explain what your resource "
        "is all "
        "about! It’s worth remembering that you are using the space to "
        "communicate to two "
        "different audiences. Firstly, think about what fellow teachers "
        "would like "
        "to know, such as exactly what the resource contains and how it "
        "could be used in the classroom. Secondly, the words you include "
        "on this page are also talking to internal and external search "
        "engines."
        " External search engines, like Google, show the first 155 characters "
        "of the resource description, so make sure you take advantage "
        "of these "
        "characters by using lots of relevant keywords as part of an "
        "enticing pitch.",
    )
    card_description = forms.CharField(
        max_length=1000,
        widget=forms.Textarea,
        help_text=(
            "If you enter text here, it will be used in the 'card' description "
            "box on the home page. Max 1000 characters."
        ),
    )
    resource_type = forms.ModelChoiceField(queryset=ResourceType.objects.all())
    age_range = forms.ChoiceField(
        choices=AGE_RANGE_CHOICES,
        help_text="Try to be accurate in your choice of age range so that your resource "
        "shows up in the correct searches. (Although we don't have searches yet!)",
    )
    curriculum = forms.ChoiceField(
        choices=CURRICULUM_CHOICES,
        required=False,
    )
    main_resource_category = forms.ModelChoiceField(
        queryset=ResourceCategory.objects.all(),
        help_text="Categorise your resource by subject so it shows up in the correct "
        "searches. It's a good idea to limit the number of subjects you select "
        "to one or two to make your resource easier to find.",
    )
    subcategories = forms.MultipleChoiceField(
        required=False,
    )

    pdf_files = forms.FileField(
        widget=forms.TextInput(
            attrs={
                "multiple": True,
                "type": "File",
                "required": True,
            },
        ),
        required=False,
        help_text="You can multi-select up to 20 .pdf files here.",
        label="PDF files",
    )
    thumbnail_files = forms.FileField(
        widget=forms.TextInput(
            attrs={
                "multiple": True,
                "type": "File",
                "required": True,
            },
        ),
        required=False,
        label="Cover images",
        help_text="Your cover image will be displayed in the search results and as "
        "the first image on your resource page in the preview function. "
        "It is important to add an eye catching cover image that gives "
        "other teachers an idea about what your resource contains. "
        "You can multi-select up to 5 .png or .jpg files here.",
    )
    pdf_files.widget.attrs.update({"class": "file_upload", "accept": ".pdf"})
    thumbnail_files.widget.attrs.update({"class": "file_upload", "accept": ".png,.jpg"})
    feature_slot = forms.IntegerField(
        min_value=1,
        max_value=3,
        required=False,
        help_text=(
            "Please enter either 1, 2 or 3 here. This will dictate where on the page "
            "this resource will feature on the main list page."
        ),
    )

    def clean_thumbnail_files(self):
        thumbnail_files = self.files.getlist("thumbnail_files")
        if not thumbnail_files:
            raise forms.ValidationError("Please select at least one thumbnail file.")
        acceptable = ["image/png", "image/jpeg"]
        for f in thumbnail_files:
            content_type = magic.from_buffer(f.file.read(), mime=True)
            f.file.seek(0)
            if content_type not in acceptable:
                raise forms.ValidationError("Please select only PNG or JPG files.")
        if len(thumbnail_files) > ALLOWED_THUMBNAILS:
            raise forms.ValidationError("Please select up to 5 files.")
        return thumbnail_files

    def clean_pdf_files(self):
        pdf_files = self.files.getlist("pdf_files")
        if not pdf_files:
            raise forms.ValidationError("Please select at least one PDF file.")
        acceptable = ["application/pdf"]
        for f in pdf_files:
            content_type = magic.from_buffer(f.file.read(), mime=True)
            f.file.seek(0)
            if content_type not in acceptable:
                raise forms.ValidationError("Please select only PDF files.")
        if len(pdf_files) > ALLOWED_PDFS:
            raise forms.ValidationError("Please select up to 20 PDF files.")
        return pdf_files


class ResourceUpdateMetadataForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.add_input(Submit("submit", "Submit"))
        self.fields["subcategories"].queryset = ResourceSubcategory.objects.all().order_by("name")

    error_css_class = "error"
    required_css_class = "required"

    class Meta:
        model = Resource
        fields = [
            "name",
            "description",
            "card_description",
            "resource_type",
            "age_range",
            "curriculum",
            "main_resource_category",
            "subcategories",
            "feature_slot",
        ]


class ResourceUpdatePDFsForm(forms.Form):
    def __init__(self, cancel_url: str, *args, **kwargs):
        try:
            self.resource = kwargs.pop("resource")
        except KeyError:
            pass
        super().__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.layout = Layout(
            Field("pdf_files"),
            FormActions(
                Submit("submit", "Submit", css_class="btn btn-primary"),
                Button("cancel", "Cancel", css_class="btn btn-danger", onclick=f"location.href=''"),
            ),
        )

    pdf_files = forms.FileField(
        widget=forms.TextInput(
            attrs={
                "multiple": True,
                "type": "File",
                "required": True,
            },
        ),
        required=False,
        help_text="You can multi-select up to 20 .pdf files here.",
        label="PDF files",
    )

    pdf_files.widget.attrs.update({"class": "file_upload", "accept": ".pdf"})

    def clean_pdf_files(self):
        pdf_files = self.files.getlist("pdf_files")
        if not pdf_files:
            raise forms.ValidationError("Please select at least one PDF file.")
        acceptable = ["application/pdf"]
        for f in pdf_files:
            content_type = magic.from_buffer(f.file.read(), mime=True)
            f.file.seek(0)
            if content_type not in acceptable:
                raise forms.ValidationError("Please select only PDF files.")
        if len(pdf_files) > ALLOWED_PDFS:
            raise forms.ValidationError("Please select up to 20 PDF files.")
        return pdf_files


class ResourceUpdateThumbnailsForm(forms.Form):
    def __init__(self, *args, **kwargs):
        try:
            self.resource = kwargs.pop("resource")
        except KeyError:
            pass
        super().__init__(*args, **kwargs)
        self.helper = FormHelper(self)
        self.helper.add_input(Submit("submit", "Submit"))

    thumbnail_files = forms.FileField(
        widget=forms.TextInput(
            attrs={
                "multiple": True,
                "type": "File",
                "required": True,
            },
        ),
        required=False,
        label="Thumbnail files",
        help_text="You can upload 5 files.",
    )
    thumbnail_files.widget.attrs.update({"class": "file_upload", "accept": ".png,.jpg"})

    def clean_thumbnail_files(self):
        thumbnail_files = self.files.getlist("thumbnail_files")
        if not thumbnail_files:
            raise forms.ValidationError("Please select at least one thumbnail file.")
        acceptable = ["image/png", "image/jpeg"]
        for f in thumbnail_files:
            content_type = magic.from_buffer(f.file.read(), mime=True)
            f.file.seek(0)
            if content_type not in acceptable:
                raise forms.ValidationError("Please select only PNG or JPG files.")
        if len(thumbnail_files) > ALLOWED_THUMBNAILS:
            raise forms.ValidationError("Please select up to 5 files.")
        return thumbnail_files